Sibeesh Passion

Top Menu

  • Home
  • Search
  • About
  • Privacy Policy

Main Menu

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Home
  • Search
  • About
  • Privacy Policy

logo

Sibeesh Passion

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment

  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins

  • Post Messages to Microsoft Teams Using Python

  • Get Azure Blob Storage Blob Metadata Using PowerShell

  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines

.NETASP.NET
Home›.NET›Programmatically Extract or Unzip Zip,Rar Files And Check

Programmatically Extract or Unzip Zip,Rar Files And Check

By SibeeshVenu
February 25, 2016
3078
2
Share:
Compression_References

In this pose we will see how we can extract or unzip the uploaded files and check for some files in it in a in a programmatic manner. 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 it is uploaded we will check the same by looping through it. For the client side coding, we uses 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:

  • Programmatically Extract or Unzip Zip,Rar Files And Check
  • Background

    As you are aware most websites accepts only .zip or any other zipped formats, this is for ensuring that only less amount of data is being uploaded to the server. We can reduce almost 60 percentage of the size if we zipped 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 with extension of .sql, .ico or .txt? What if you want to intimate user that the uploaded items does 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 (http://sibeeshpassion.com/) 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.

    [csharp]
    public ActionResult Index()
    {
    return View();
    }
    [/csharp]

    Update the view

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

    [html]
    <input type="file" name="FileUpload1" id="fileUpload" placeholder="Please select the file" /><br />
    <input id="btnUploadFile" type="button" value="Upload File" />
    <div id="message"></div>
    [/html]

    Add the JS references

    Add the references as follows.

    [html]
    <script src="~/scripts/jquery-1.10.2.min.js"></script>
    <script src="~/scripts/MyScript.js"></script>
    [/html]

    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 as simple as default one. And to be frank I am not a good designer 🙂

    [css]
    <style>
    #fileUpload {
    border: 1px solid #ccc;
    padding: 10px;
    border-radius: 5px;
    font-size: 14px;
    font-family: cursive;
    color: blue;
    }

    #btnUploadFile {
    border: 1px solid #ccc;
    padding: 10px;
    border-radius: 5px;
    font-size: 14px;
    font-family: cursive;
    color: blue;
    }

    #message {
    border-radius: 5px;
    font-size: 14px;
    font-family: cursive;
    color: blue;
    margin-top: 15px;
    }
    h2 {
    border-radius: 5px;
    font-size: 20px;
    font-family: cursive;
    color: blue;
    margin-top: 15px;
    }
    </style>
    [/css]

    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.

    [js]
    $(document).ready(function () {
    $(‘#btnUploadFile’).on(‘click’, function () {
    var data = new FormData();
    var files = $("#fileUpload").get(0).files;
    // Add the uploaded image content to the form data collection
    if (files.length > 0) {
    data.append("UploadedImage", files[0]);
    }
    // Make Ajax request with the contentType = false, and procesDate = false
    var ajaxRequest = $.ajax({
    type: "POST",
    url: "Home/Upload",
    contentType: false,
    processData: false,
    data: data,
    success: function (data) {
    $(‘#message’).html(data);
    },
    error: function (e)
    {
    console.log(‘Oops, Something went wrong!.’ + e.message);
    }
    });
    ajaxRequest.done(function (xhr, textStatus) {
    // Do other operation
    });
    });
    });
    [/js]

    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.

    [csharp]
    public JsonResult Upload()
    {
    string isValid = checkIsValid(Request.Files);
    return Json(isValid, JsonRequestBehavior.AllowGet);
    }
    [/csharp]

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

    [csharp]
    using System.IO.Compression;
    [/csharp]

    Now you will be shown an error as “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 uses 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 differs according to your framework version

    Compression_References

    Compression_References

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

    [csharp]
    private string checkIsValid(HttpFileCollectionBase files)
    {
    string isValid = string.Empty;
    try
    {
    foreach (string upload in Request.Files)
    {
    if (Request.Files[upload].ContentType == "application/octet-stream") //Content type for .zip is application/octet-stream
    {
    if (Request.Files[upload].FileName != "")
    {
    string path = AppDomain.CurrentDomain.BaseDirectory + "/ App_Data / uploads /";
    if (!Directory.Exists(path))
    {
    // Try to create the directory.
    DirectoryInfo di = Directory.CreateDirectory(path);
    }

    string filename = Path.GetFileName(Request.Files[upload].FileName);
    string pth = Path.Combine(path, filename);
    Request.Files[upload].SaveAs(pth);
    isValid = CheckForTheIcon(pth);
    }
    }
    else
    {
    isValid = "Only .zip files are accepted.";
    }
    }
    return isValid;
    }
    catch (Exception)
    {
    return "Oops!. Something went wrong";
    }
    }
    [/csharp]

    As you can see we are looping through the HttpFileCollectionBase files and checks for the content type first.

    Please be noted 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 function CheckForTheIcon(pth). So our next thing we need to do is to create the function CheckForTheIcon().

    [csharp]
    private string CheckForTheIcon(string strPath)
    {
    string result = string.Empty;
    try
    {
    using (ZipArchive za = ZipFile.OpenRead(strPath))
    {
    foreach (ZipArchiveEntry zaItem in za.Entries)
    {
    if (zaItem.FullName.EndsWith(".ico", StringComparison.OrdinalIgnoreCase))
    {
    result = "Success";
    }
    else
    {
    result = "No ico files has been found";
    }
    }
    }
    return result;
    }
    catch (Exception)
    {
    result = "Oops!. Something went wrong";
    return result;
    }
    }
    [/csharp]

    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 which is needed? Have you ever wanted to do this requirement? Could you find this post as useful? I hope you liked this article. Please share 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.

    Kindest Regards
    Sibeesh Venu

    TagsAsp.NetCSharpExtract FilesHttpFileCollectionBaseMVCSystem.IO.CompressionSystem.IO.Compression.FileSystemUnzip FilesUpload in MVCZipArchive
    Previous Article

    Change Page Layout Dynamically Using jQuery Layout ...

    Next Article

    jQuery Datatable With Server Side Data

    0
    Shares
    • 0
    • +
    • 0
    • 0
    • 0

    SibeeshVenu

    I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer.

    Related articles More from author

    • Upload Images To Azure Media Service Home Page
      Azure

      Upload Files To Azure Media Service From Server Side In MVC

      June 30, 2016
      By SibeeshVenu
    • .NETASP.NET

      Determine Which Browser Your Application is Running In

      June 17, 2015
      By SibeeshVenu
    • Empty Solution
      .NETASP.NETSQL

      Encrypt And Decrypt ConnectionString In Web.Config File

      May 16, 2016
      By SibeeshVenu
    • jQuery Datatable With Server Side Data
      .NETAngularWeb API

      jQuery Datatable With Server Side Data

      February 25, 2016
      By SibeeshVenu
    • Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_
      .NETAngularASP.NETWeb API

      Angular JS AutoComplete In MVC With Web API

      March 24, 2016
      By SibeeshVenu
    • Excel Export In MDX
      .NETASP.NETMDX QuerySQL

      Export MDX Result As Excel

      October 28, 2015
      By SibeeshVenu
    0

    My book

    Asp Net Core and Azure with Raspberry Pi Sibeesh Venu

    YouTube

    MICROSOFT MVP (2016-2022)

    profile for Sibeesh Venu - Microsoft MVP

    Recent Posts

    • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment
    • Build, Deploy, Configure CI &CD Your Static Website in 5 mins
    • Easily move data from one COSMOS DB to another
    • .NET 8 New and Efficient Way to Check IP is in Given IP Range
    • Async Client IP safelist for Dot NET
    • Post Messages to Microsoft Teams Using Python
    • Get Azure Blob Storage Blob Metadata Using PowerShell
    • Deploy .net 6 App to Azure from Azure DevOps using Pipelines
    • Integrate Azure App Insights in 1 Minute to .Net6 Application
    • Azure DevOps Service Connection with Multiple Azure Resource Group

    Tags

    Achievements (35) Angular (14) Angular 5 (7) Angular JS (15) article (10) Article Of The Day (13) Asp.Net (14) Azure (65) Azure DevOps (10) Azure Function (10) Azure IoT (7) C# (17) c-sharp corner (13) Career Advice (11) chart (11) CSharp (7) CSS (7) CSS3 (6) HighChart (10) How To (9) HTML5 (10) HTML5 Chart (11) Interview (6) IoT (11) Javascript (10) JQuery (82) jquery functions (9) JQWidgets (15) JQX Grid (17) Json (7) Microsoft (8) MVC (20) MVP (9) MXChip (7) News (18) Office 365 (7) Products (10) SQL (20) SQL Server (15) Visual Studio (10) Visual Studio 2017 (7) VS2017 (7) Web API (12) Windows 10 (7) Wordpress (9)
    • .NET
    • Achievements
    • ADO.NET
    • Android
    • Angular
    • Arduino
    • Article Of The Day
    • ASP.NET
    • Asp.Net Core
    • Automobile
    • Awards
    • Azure
    • Azure CDN
    • azure devops
    • Blockchain
    • Blog
    • Browser
    • C-Sharp Corner
    • C#
    • Career Advice
    • Code Snippets
    • CodeProject
    • Cognitive Services
    • Cosmos DB
    • CSS
    • CSS3
    • Data Factory
    • Database
    • Docker
    • Drawings
    • Drill Down Chart
    • English
    • Excel Programming
    • Exporting
    • Facebook
    • Fun
    • Gadgets
    • GitHub
    • GoPro
    • High Map
    • HighChart
    • How to
    • HTML
    • HTML5
    • Ignite UI
    • IIS
    • Interview
    • IoT
    • JavaScript
    • JQuery
    • jQuery UI
    • JQWidgets
    • JQX Grid
    • Json
    • Knockout JS
    • Linux
    • Machine Learning
    • Malayalam
    • Malayalam Poems
    • MDX Query
    • Microsoft
    • Microsoft ADOMD
    • Microsoft MVP
    • Microsoft Office
    • Microsoft Technologies
    • Microsoft Windows
    • Microsoft Windows Server
    • Mobile
    • MongoDB
    • Monthly Winners
    • MVC
    • MVC Grid
    • MySQL
    • News
    • Node JS
    • npm
    • Number Conversions
    • October 2015
    • Office 365
    • Office Development
    • One Plus
    • Outlook
    • Page
    • PHP
    • Poems
    • PowerShell
    • Products
    • Q&A
    • Raspberry PI
    • React
    • SEO
    • SharePoint
    • Skype
    • Social Media
    • Software
    • Spire.Doc
    • Spire.PDF
    • Spire.XLS
    • SQL
    • SQL Server
    • SSAS
    • SSMS
    • Storage In HTML5
    • Stories
    • Third Party Software Apps
    • Tips
    • Tools
    • Translator Text
    • Uncategorized
    • Unit Testing
    • UWP
    • VB.Net
    • Videos
    • Virtual Machine
    • Visual Studio
    • Visual Studio 2017
    • Wamp Server
    • Web API
    • Web Platform Installer
    • Webinars
    • WebMatrix
    • Windows 10
    • Windows 7
    • Windows 8.1
    • Wordpress
    • Writing

    ABOUT ME

    I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer. If you would like to know more about me, you can read my story here.

    Contact Me

    • info@sibeeshpassion.com

    Pages

    • About
    • Search
    • Privacy Policy
    • About
    • Search
    • Privacy Policy
    © Copyright Sibeesh Passion 2014-2025. All Rights Reserved.
    Go to mobile version