c# .net

How to compress file c# .net?

How to compress file c# .net?, someone asked me to explain?

In this article, I will show you how to compress a file using System.IO.Compression namespace in c#.net. 

you can upload a file using fileupload control and perform a compression with some of the functions and create a zip file that has a .zip file name extension. 

      <form id="form1" runat="server">
        <div style="border: 1px solid #357ae8; padding-top: 15px; width: 500px; height: 350px">
            <h1 style="color: #3d75bd;">Compress file using c# .net?</h1>
            <br />
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="btnUpload" Text="Upload to FTP" runat="server" OnClick="FTPUpload" />
        </div>
    </form> 


protected
void FTPUpload(object sender, EventArgs e)
    {
       Compress();
    }   

    public void Compress()
    {
        string fileToBeCompressed = Path.GetFileName(FileUpload1.FileName);
        string zipFile = Path.GetFileName(FileUpload1.FileName) + ".zip";
        string zipFilePath = Path.Combine(Server.MapPath("~/Uploads"), zipFile);
        byte[] fileBytes = FileUpload1.FileBytes;
        using (FileStream target = new FileStream(zipFilePath, FileMode.Create, FileAccess.Write))
        using (GZipStream zipstream = new GZipStream(target, CompressionMode.Compress))
        {
           byte[] data = fileBytes;
           zipstream.Write(data, 0, data.Length);
           zipstream.Flush();
        }
    }

       using (GZipStream zipstream = new GZipStream(target, CompressionMode.Compress))
        {
           byte[] data = fileBytes;
           zipstream.Write(data, 0, data.Length);
           zipstream.Flush();
        }
    } 

Output:

How to compress file csharp .net

Post your comments / questions