Programmatically Extract or Unzip Zipand Rar Files, And Check For Files

We will use a normal MVC application to work with this demo. We will use Microsoft System.IO.Compression, System.IO.Compression.FileSystem namespaces and the classes, for example, ZipArchive, in the namespace for extracting or unzipping the files we upload. Once they are uploaded we will check the same by looping through it. For the client side coding, wewill use jQuery. I guess this is enough for the introduction, now we will move on to our application. Let us create it. I hope you will like this article.

Download the source code

You can always download the source code here:

Background

As you are aware that most websites accept only .zip or any other zipped formats?  This is for ensuring that only the least amount of data is being uploaded to the server. We can reduce almost 60 percent of the size if we zip the same. Now the problem is, how you can validate any zipped item which is uploaded to your site? How can you check for any particular file in that zipped item, for example, if you need to find out any files withthe extension of .sql, .ico or .txt? What if you want to inform the user that the uploaded items do not have any particular file that must be needed? You need to loop through the contents available in it, right? This is what we are going to discuss in this post. I had a situation of uploading my old back ups of my personal website and after uploading I wanted to check whether the uploaded .zip file has .ico file in it. The process we are going to do is listed below.

  • Create a MVC application
  • Install jQuery
  • Create Controller and View
  • Upload Action Using jQuery
  • Add System.IO.Compression, System.IO.Compression.FileSystem references
  • Checks for the file using ZipArchive class

Using the code

Now we will move into the coding part. I hope your MVC application is ready for action with all the needed packages.

Create a controller

Now we will create a controller, view with an action in it as follows.

  1. public ActionResult Index()  
  2. {  
  3.     return View();  
  4. }  

Update the view

Now in the view, we will add a file upload and other needed elements.

  1. <input type="file" name="FileUpload1" id="fileUpload" placeholder="Please select the file" /><br />  
  2. <input id="btnUploadFile" type="button" value="Upload File" />  
  3. <div id="message"></div>  

Add the JS references

Add the references as follows.

  1. <script src="~/scripts/jquery-1.10.2.min.js"></script>  
  2. <script src="~/scripts/MyScript.js"></script>  

Here MyScript.js is where we are going to write some scripts.

Style the elements (Optional)

You can style your view as follows. This step is absolutely optional, for me the view should not be as simple as default one. And to be frank I am not a good designer. 

  1. <style>  
  2.     #fileUpload  
  3.     {  
  4.         border: 1px solid #ccc;  
  5.         padding: 10px;  
  6.         border-radius: 5px;  
  7.         font-size: 14px;  
  8.         font-family: cursive;  
  9.         color: blue;  
  10.     }  
  11.      
  12.     #btnUploadFile  
  13.     {  
  14.         border: 1px solid #ccc;  
  15.         padding: 10px;  
  16.         border-radius: 5px;  
  17.         font-size: 14px;  
  18.         font-family: cursive;  
  19.         color: blue;  
  20.     }  
  21.      
  22.     #message  
  23.     {  
  24.         border-radius: 5px;  
  25.         font-size: 14px;  
  26.         font-family: cursive;  
  27.         color: blue;  
  28.         margin-top: 15px;  
  29.     }  
  30.       
  31.     h2 {  
  32.         border-radius: 5px;  
  33.         font-size: 20px;  
  34.         font-family: cursive;  
  35.         color: blue;  
  36.         margin-top: 15px;  
  37.     }  
  38. </style>  

Add the upload action in script

Now it is time to create upload action. For that, please go to the script file MyScript.js and do the coding as follows.

  1. $(document).ready(function()  
  2.   {  
  3.     $('#btnUploadFile').on('click', function()  
  4.        {  
  5.         var data = new FormData();  
  6.         var files = $("#fileUpload").get(0).files;  
  7.         // Add the uploaded image content to the form data collection  
  8.         if (files.length > 0)   
  9.         {  
  10.             data.append("UploadedImage", files[0]);  
  11.         }  
  12.         // Make Ajax request with the contentType = false, and procesDate = false  
  13.         var ajaxRequest = $.ajax  
  14.         ({  
  15.             type: "POST",  
  16.             url: "Home/Upload",  
  17.             contentType: false,  
  18.             processData: false,  
  19.             data: data,  
  20.             success: function(data)  
  21.             {  
  22.                 $('#message').html(data);  
  23.             },  
  24.             error: function(e)  
  25.             {  
  26.                 console.log('Oops, Something went wrong!.' + e.message);  
  27.             }  
  28.         });  
  29.         ajaxRequest.done(function(xhr, textStatus)  
  30.         {  
  31.             // Do other operation  
  32.         });  
  33.     });  
  34. });  

If you are not aware of uploading and downloading in MVC, I strongly recommend you to have a look here: Uploading and Downloading in MVC Step-by-Step.

So we have set Home/Upload as the URL action in our Ajax function, right? So we are going to create that action. Go to your controller and create a JsonResult action as follows.

  1. public JsonResult Upload()   
  2. {  
  3.     string isValid = checkIsValid(Request.Files);  
  4.     return Json(isValid, JsonRequestBehavior.AllowGet);  
  5. }  

So we have done that too, now stop for a while. To work with ZipArchive class you must include the namespace as listed below.

  1. using System.IO.Compression;  

Now you will be shown an error; “Are you missing an assembly reference?” Yes, we are. We have not added that references, right? So now we are going to add the references for System.IO.Compression and System.IO.Compression.FileSystem.

Right click on Reference in your project and browse for the references. If you use Visual Studio 2015, the references will be in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6. Please be noted that the folder names will differ according to your framework version.

Compression_References
                                                         Compression_References

Now we will go back to our controller and write the code for the function checkIsValid(Request.Files)

  1. private string checkIsValid(HttpFileCollectionBase files)  
  2. {  
  3.     string isValid = string.Empty;  
  4.     try  
  5.     {  
  6.         foreach(string upload in Request.Files)  
  7.         {  
  8.             if (Request.Files[upload].ContentType == "application/octet-stream"//Content type for .zip is application/octet-stream  
  9.             {  
  10.                 if (Request.Files[upload].FileName != "")  
  11.                 {  
  12.                     string path = AppDomain.CurrentDomain.BaseDirectory + "/ App_Data / uploads /";  
  13.                     if (!Directory.Exists(path))  
  14.                     {  
  15.                         // Try to create the directory.  
  16.                         DirectoryInfo di = Directory.CreateDirectory(path);  
  17.                     }  
  18.                     string filename = Path.GetFileName(Request.Files[upload].FileName);  
  19.                     string pth = Path.Combine(path, filename);  
  20.                     Request.Files[upload].SaveAs(pth);  
  21.                     isValid = CheckForTheIcon(pth);  
  22.                 }  
  23.             } else  
  24.             {  
  25.                 isValid = "Only .zip files are accepted.";  
  26.             }  
  27.         }  
  28.         return isValid;  
  29.     } catch (Exception)  
  30.     {  
  31.         return "Oops!. Something went wrong";  
  32.     }  
  33. }  

As you can see we are looping through the HttpFileCollectionBase files and checks for the content type first. Please note that the content type for the .zip file is application/octet-stream.

Once the checking is done, we will save the files to a folder, we will send the path to the functionCheckForTheIcon(pth). So the next thing we need to do is to create the function CheckForTheIcon().private string CheckForTheIcon(string strPath).

  1. {  
  2.     string result = string.Empty;  
  3.     try  
  4.     {  
  5.         using(ZipArchive za = ZipFile.OpenRead(strPath))  
  6.         {  
  7.             foreach(ZipArchiveEntry zaItem in za.Entries)  
  8.             {  
  9.                 if (zaItem.FullName.EndsWith(".ico", StringComparison.OrdinalIgnoreCase))  
  10.                 {  
  11.                     result = "Success";  
  12.                 } else  
  13.                 {  
  14.                     result = "No ico files has been found";  
  15.                 }  
  16.             }  
  17.         }  
  18.         return result;  
  19.     } catch (Exception)  
  20.     {  
  21.         result = "Oops!. Something went wrong";  
  22.         return result;  
  23.     }  
  24. }  

As you can see we are looping through each ZipArchive class items and checks for the ‘.ico’ file in it. So if there is no error and there is ‘.ico’ file in the uploaded item zip item, you will get the message as “Success: or if it does not contain the ‘.ico’ file, you will get the message as “No ico files has been found”.

Now it is time to see our output. Please run your application.

Output

If_you_try_to_upload_not_zipped_item
                                    If_you_try_to_upload_not_zipped_item

If_you_try_to_upload_zipped_item_which_does_not_have_ico_file                         If_you_try_to_upload_zipped_item_which_does_not_have_ico_file
If_you_try_to_upload_zipped_item_which_have_ico_file
                                 If_you_try_to_upload_zipped_item_which_have_ico_file

Conclusion

Did I miss anything that you may think is needed? Have you ever wanted to do this requirement? Did you find this post useful? I hope you liked this article. Please sharewith me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

Please see this article in my blog here.

Read more articles on ASP.NET:

Up Next
    Ebook Download
    View all
    Learn
    View all