In this article, we are going to learn how to create a zip file of uploaded files and store them in a folder using ASP.NET Core in simple steps.

Create a Zip file

Useful Links

How to Upload Files and Save in Database in ASP.NET Core MVC

https://tutexchange.com/how-to-upload-files-and-save-in-database-in-asp-net-core-mvc/

File upload in ASP.NET Core MVC (Storing in Folder)

https://tutexchange.com/file-upload-in-asp-net-core-mvc-storing-in-folder/

Uploading Multiple Files in ASP.NET Core MVC (Storing in a Folder)

https://tutexchange.com/uploading-multiple-files-in-asp-net-core-mvc-storing-in-folder/

Table of Contents

  • Creating Project
  • Project structure
  • Adding Controller and View
  • Adding System.IO.Compression package NuGet Package
  • Adding a “Create” View to Upload files
  • Create View Design
  • Creating Zip Process
  • Adding New HttpPost Action Method “Create” in Demo Controller
  • Final Output
  • Conclusion

Let’s Get Started

Creating Project

We are going to create a new application, as shown below.

Creating Project

Next, we are going to set Project Name DemoZipApplication and location. In the last part, we will choose the .Net Core framework and ASP.NET Core Version 6.0 as the framework for the application and a few advanced settings such as configuring HTTPS and enabling docker; we are not going to enable docker settings for this project.

Creating Project

Now finally, click on create button to create a project.

Project structure

The project structure is generated according to the configuration.

Project structure

After creating the project next, we are going to Controller and View.

Adding Controller and View

We are going to add a Controller Name “Demo“.

using Microsoft.AspNetCore.Mvc;
namespace DemoZipApplication.Controllers
{
    public class DemoController : Controller
    {
        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }
    }
}

Adding System.IO.Compression package NuGet Package

For doing zip we are going to System.IO.Compression package.

System.IO.Compression

Contains classes that provide basic compression and decompression services for streams.

System.IO.Compression

After adding the NuGet package Next, we are going to Add a View.

Adding a “Create” View to Upload files

We are going to add Create View where we are going to add file upload control where users can upload files which will be stored in a folder.

The added Form tag is encoded as “multipart/form-data” and to the file tag, we have added a “multiple” attribute to select more than one file.

<div class="col-md-12">
    <form asp-controller="Demo" autocomplete="off" asp-antiforgery="true" enctype="multipart/form-data" asp-action="Create" method="post">
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Files Uploads</h3>
        </div>
        <div class="card-body register-card-body">
            <div class="form-row">
                <div class="col-md-4">
                   
                    <div class="text-danger" asp-validation-summary="ModelOnly"></div>
                    <input type="file" multiple="multiple" name="fileupload"/>
                 
                </div>
            </div>
        </div>
        <div class="card-footer">
            <button type="submit" id="btnupload" class="btn btn-success">Upload Files</button>

            <a class="btn btn-danger" asp-controller="Demo" asp-action="Create">Clear</a>

        </div>
    </div>
    </form>
</div>

Create View Design

This is how Create View looks like when it is rendered.

Create View Design

Next, we are going to create a zip on the fly.

Creating Zip Process

  1. Uploading files
  2. Create a new folder inside the UploadedFiles folder and name the folder in this format (yyyyMMddHHmmss).
  3. Storing uploaded files to a folder which we have created recently.
  4. Next, we are going to get a recently created folder and create a zip of that folder and store it in the CreatedZip folder.

Adding New HttpPost Action Method “Create” in Demo Controller

In this action method, we have written code for Create Zip on the fly.

  [HttpPost]
        public async Task<IActionResult> Create(IFormFile filedata)
        {
            var currentdatefolder = DateTime.Now.ToString("yyyyMMddHHmmss");
            var files = HttpContext.Request.Form.Files;
            if (files.Any())
            {
                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        //Getting FileName
                        var fileName = Path.GetFileName(file.FileName);
                        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "ZipsUpload", currentdatefolder);
                        if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "ZipsUpload",
                            currentdatefolder)))
                        {
                            System.IO.Directory.CreateDirectory(path);
                        }

                        var storingfilePath = $"{new PhysicalFileProvider(path).Root}{$@"{fileName}"}";
                        await using FileStream fs = System.IO.File.Create(storingfilePath);
                        await file.CopyToAsync(fs);
                        fs.Flush();

                    }
                }


                var zippath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "ZipsUpload", currentdatefolder);
                var sourcezipPath = new PhysicalFileProvider(zippath).Root;
                var zipname = $"File_{currentdatefolder}.zip";
                var destinationPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "CreatedZip", zipname);
                ZipFile.CreateFromDirectory(sourcezipPath, destinationPath);

                return Json(new { status = true, Message = "Files Uploaded Successfully!" });
            }



            return View();
        }

If you see the above code we will get all files which are uploaded in IFormCollection.

After getting multiple files we are going to iterate it because we are going to receive multiple files in the request.

 var files = HttpContext.Request.Form.Files;
            if (files.Any())
            {
                foreach (var file in files)
                {

Next, we are going to check if does folder exists if not then we are going to create a new folder (currentdatefolder) inside the “UploadedFiles” folder.

Example: – we have a folder named “20221106115432” inside this folder we are going to store all uploaded files.

UploadedFiles folder

After storing files in a folder, next we are going to get the recently created folder name “20221106115432” and generate a folder path and this path will be the source path “sourcezipPath”.

Next, you will think about what the will be zip name right.

The zip name will be the name of the folder only that we have created.

var zipname = $"File_{currentdatefolder}.zip";

After creating the zip, we are going to store it in the CreatedZip folder which is our destination folder.

 CreatedZip folder

For creating a zip, we are going to call the method ZipFile.CreateFromDirectory.

ZipFile.CreateFromDirectory

Creates a zip archive that contains the files and directories from the specified directory.

To ZipFile.CreateFromDirectory method we are going to pass to parameters one will be the source of files and another will be the location where to store that created files.

ZipFile.CreateFromDirectory(storingzipPath, destinationPath);
ZipFile.CreateFromDirectory

Now everything is set let’s run the application once and create a zip file.

Final Output

You can see below View is shown when we upload the file and the zip is created successfully.

Final Output

when we upload files we are creating zip files on the fly and storing in a folder below is the output of it.

Solution Explorer View of Create zip files

Now let’s check we have created a folder but does it have all files which we have uploaded?

I have opened one of the zip which we have created and it has files which we have uploaded wow we made it.

zip folder view

Conclusion

Wow, finally we are at the end of this article where we have learned how to create a simple zip file in ASP.NET Core using the System.IO.Compression Package.

Hope you Liked this Article Please share it if possible.

References

https://learn.microsoft.com/en-us/dotnet/api/system.io.compression?view=net-6.0

https://www.facebook.com/Tutexchange/

By Saineshwar

Microsoft MVP for Developer Technologies | C# Corner MVP | Code project MVP | Senior Technical Lead | Author | Speaker | Love .Net | Full Stack developer | Open source contributor.