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:
Post your comments / questions
Recent Article
- How to check PAN-Aadhaar is Linked or NOT?
- How to customize pagination for django admin?
- How to fix HAXM is not installed |in Android Studio
- How to fix CMOS Checksum Error in Computer or Laptop | SOLVED
- Reactivating windows after a Hardware change on PC or Laptop
- FIXED: Windows reported that the hardware of your device has changed. Error code :0xc004F211
- "redirect" is not defined pylance("reportUndefinedVariable)
- This action cannot be completed because the file is open in SQL Server(SQLEXPRESS) - FIXED
Related Article