• No results found

Zip Unzip

N/A
N/A
Protected

Academic year: 2021

Share "Zip Unzip"

Copied!
18
0
0

Loading.... (view fulltext now)

Full text

(1)

Compress / Gzip files in .Net 2.0 using C#

Compress / Gzip files in .Net 2.0 using C#

(System.IO.Compression)

(System.IO.Compression)

using System.IO.Compression; using System.IO.Compression;

public class Compress public class Compress {

{

string _folderpath=""; string _folderpath=""; public string folderpath public string folderpath {

{

get { return _folderpath; } get { return _folderpath; } set { _folderpath = value; } set { _folderpath = value; } }

}

public void compressfolder() public void compressfolder() {

{

DirectoryInfo dir=new DirectoryInfo(_folderpath); DirectoryInfo dir=new DirectoryInfo(_folderpath); foreach (FileInfo fl in dir.GetFiles())

foreach (FileInfo fl in dir.GetFiles()) {

{

//Open the file as a FileStream object. //Open the file as a FileStream object.

FileStream infile = new FileStream(fl.FullName, FileStream infile = new FileStream(fl.FullName, FileMode.Open,

FileMode.Open,

FileAccess.Read, FileShare.Read); FileAccess.Read, FileShare.Read);

byte[] buffer = new byte[infile.Length]; byte[] buffer = new byte[infile.Length]; // Read the file to ensure it is readable. // Read the file to ensure it is readable.

int count = infile.Read(buffer, 0, buffer.Length); int count = infile.Read(buffer, 0, buffer.Length); if (count != buffer.Length) if (count != buffer.Length) { { infile.Close(); infile.Close();

Console.WriteLine("Test Failed: Unable to read Console.WriteLine("Test Failed: Unable to read data from file");

data from file");

return; return; } } infile.Close(); infile.Close(); Stream fs = File.Create(_folderpath + Stream fs = File.Create(_folderpath + Path.ChangeExtension(fl.Name + fl.Extension , ".gz")); Path.ChangeExtension(fl.Name + fl.Extension , ".gz"));

// Use the newly created stream for the compressed // Use the newly created stream for the compressed data.

data.

GZipStream gZip = new GZipStream(fs, GZipStream gZip = new GZipStream(fs, CompressionMode.Compress, true); CompressionMode.Compress, true); Console.WriteLine("Compression"); Console.WriteLine("Compression"); gZip.Write(buffer, 0, buffer.Length); gZip.Write(buffer, 0, buffer.Length); // Close the stream.

// Close the stream. gZip.Close();

gZip.Close();

Console.WriteLine("Original size: {0}, Compressed Console.WriteLine("Original size: {0}, Compressed size: {1}", size: {1}", buffer.Length, fs.Length); buffer.Length, fs.Length); Console.Read(); Console.Read(); } } } } } }

the class can used as below the class can used as below

Compress cm = new Compress(); Compress cm = new Compress(); cm.folderpath = @"e:\gsp\"; cm.folderpath = @"e:\gsp\"; cm.compressfolder();

(2)

UnZip files in .Net C# using SharpZipLib Open Source Library

System.IO.Compression Namespace in C# .Net provides GZipStream and DeflateStream classes to compress and de-compress gzip files and Deflated files respectively.

But our scope is to de-compress or U NZIP files using .Net C#. C# in native does not provides classes to compress (zip) or de-compress (unzip) .zip files.

#ziplib (SharpZipLib, formerly NZipLib) open source library helps us to zip an d un-zip .zip files, which is written entirely in C# for the .NET platform. It is free, C# source code included!

The required of .net version"ICSharpCode.SharpZipLib.dll" file can be downloaded from

http://www.icsharpcode.net/OpenSource/SharpZipLib/ and can referenced to the required project. The sample code for unzip .zip files in .Net C# using #ziplib (SharpZipLib) is below

Namespace used:

using System.IO;

using ICSharpCode.SharpZipLib.Zip;

public static bool UnZipFile(string InputPathOfZipFile) {

bool ret = true; try { if (File.Exists(InputPathOfZipFile)) { string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile);

using (ZipInputStream ZipStream = new ZipInputStream(File.OpenRead(InputPathOfZipFile)))

{

ZipEntry theEntry;

while ((theEntry = ZipStream.GetNextEntry()) != null) { if (theEntry.IsFile) { if (theEntry.Name != "") { string strNewFile = @"" + baseDirectory + @"\" + theEntry.Name; if (File.Exists(strNewFile)) { continue; }

using (FileStream streamWriter = File.Create(strNewFile))

{

(3)

byte[] data = new byte[2048]; while (true) { size = ZipStream.Read(data, 0, data.Length); if (size > 0) streamWriter.Write(data , 0, size); else break; } streamWriter.Close(); } } } else if (theEntry.IsDirectory) { string strNewDirectory = @"" + baseDirectory + @"\" + theEntry.Name; if (!Directory.Exists(strNewDirectory)) { Directory.CreateDirectory(strNewDir ectory); } } } ZipStream.Close(); } } }

catch (Exception ex) {

ret = false; }

return ret; }

The "UnZipFile" function can be used as

UnZipFile(@"C:\games.zip");

The above "UnZipFile" function can be used to unzip .zip files. "UnZipFile" function is self explanatory. Required file to be extracted is given to "ZipInputStream" class, which provides all entries (files/folder) found in .zip file. Each entry is checked, new folders are created for directory entry and files are created using "FileStream" for file entries. Thus required .zip files are extracted.

The files and folder unzipped are extracted to same folder as that of input file. #ziplib also compresses and de-compresses GZip, Tar and BZip2 formats.

(4)

Upload and Compressed file

Description

By using the code you can upload file and then compressed it. It Retrieve file i nformation and upload to server.

 Add below code in HTML page

<form id="form1" runat="server"> <table>

<tr> <td>

<input id="fileUpload" type="file" runat="server" /> </td> </tr> <tr> <td> <asp:TextBox ID="txtZipFileName" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:TextBox ID="txtSource" runat="server"></asp:TextBox> </td>

(5)

</tr> <tr> <td> <asp:TextBox ID="txtDestination" runat="server"></asp:TextBox> </td> </tr> <tr> <td>

<asp:Button ID="Button1" runat="server" Text="Button" />

<asp:Button ID="Button2" runat="server" Text="Upload & Compressed" />

</td> </tr> <tr>

<td>

<asp:Label ID="lblResult" runat="server" Text="Label"></asp:Label>

</td> </tr> </table> </form>

 Add below Namespaces

Imports System Imports System.IO

Imports System.IO.Compression Imports System.Diagnostics

(6)

 Add below code in Codebehind on Button1 click 

If fileUpload.PostedFile Is Nothing Then

Me.lblResult.Text = "No File Selected to Upload." Exit Sub

End If

'Retrieve file information and upload to server. Dim strName As String

strName =

System.IO.Path.GetFileName(fileUpload.PostedFile.FileName)

Try

fileUpload.PostedFile.SaveAs(Server.MapPath(strName)) Me.lblResult.Text = """" + strName + """ was uploaded successfully."

Catch ex As Exception

Me.lblResult.Text = "An Error Occured While Uploading File." End Try

 Add below code in Codebehind on Button2 click 

(7)

lblResult.Text = "You must enter what you want the name of the zip file to be"

'Change the background color to cue the user to what needs fixed

'txtZipFileName.BackColor = Color.Yellow Exit Sub

Else

'Reset the background color

'txtZipFileName.BackColor = Color.White End If

'Launch the zip.exe console app to do the actual zipping Dim i As New

System.Diagnostics.ProcessStartInfo(AppDomain.CurrentDomain.BaseDirecto ry & "zip.exe")

i.CreateNoWindow = True Dim args As String = ""

If txtSource.Text.IndexOf(" ") <> -1 Then

'we got a space in the path so wrap it in double qoutes args += """" & txtSource.Text & """"

Else

args += txtSource.Text End If

Dim dest As String = txtDestination.Text If dest.EndsWith("\") = False Then

dest += "\" End If

'Make sure the zip file name ends with a zip extension

If txtZipFileName.Text.ToUpper().EndsWith(".ZIP") = False Then txtZipFileName.Text += ".zip"

End If

dest += txtZipFileName.Text If dest.IndexOf(" ") <> -1 Then

(8)

args += (" " & """") + dest & """" Else

args += " " & dest End If

i.Arguments = args

'Mark the process window as hidden so that the progress copy window doesn't show

i.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden Dim p As System.Diagnostics.Process =

System.Diagnostics.Process.Start(i) p.WaitForExit()

Response.Write("Complete")

Compress folders with C# and the SharpZipLib

Introduction

This article shall describe an approach that may be used to collect files

from multiple locations and zip them up into a single zipped folder. The

code contained in the sample project may be useful if one needs to

gather up multiple files, zip them up, and then do something with

them such as upload the zipped files to a server location for storage

or processing. The application uses the SharpZipLib for the basis of the

compression function.

(9)

Figure 1: Demo User Interface for Folder Compression Project.

As was mentioned, the example code is dependent upon the

SharpZipLib libraries; these libraries may be downloaded from this

location: http://www.icsharpcode.net/OpenSource/SharpZipLib/

In addition to handling zip files, the library also handles tar, gzip, and

bzip2 compression.

The Solution

The solution contains a single project. The example is provided in the

form of a single Windows Forms project; the project contains a single

main form (frmMain); the references are all in the default

configuration with the exception being that the SharpZipLib DLL has

been added (first item in the reference list). Having downloaded the

DLL from the www.icsharpcode.net web, the download was installed

into the local file system and was adding by using the "Add Reference"

dialog's Browse option. All of the code necessary to drive the

(10)

Figure 2: The Solution Explorer Showing the Project.

The Code: Compress Folders - Main Form

The Compress Folders project is a Windows Forms project containing a

single form. All UI and code required by the project are contained in

the single main form (frmMain.cs).

The only references added to the project, aside from the defaults,

were those necessary to support the use of the SharpZipLib in the

project. The imports, namespace, and class declarations are as

follows:

using System; using System.Collections; using System.Text; using System.IO; using System.ComponentModel; using System.Windows.Forms; using System.Management; using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.GZip; namespace CompressFolders {

public partial class frmMain : Form {

(11)

empty form load event handler: public frmMain()

{

InitializeComponent(); }

private void frmMain_Load(object sender, EventArgs e) {

}

The next block of code is used to handle the browse button's click

event. This button is used to display the open file dialog; this dialog is

used to capture the path to a folder that the user wants to include in

the zipped folder. The code is annotated such that you may review

descriptions of what each section of the code is doing by reading

though this code block:

 /// <summary>

 /// Select files for subsequent addition to the list of   /// files to be archived

 /// </summary>

 /// <param name="sender"></param>  /// <param name="e"></param>

private void btnBrowse_Click(object sender, EventArgs e) {

 // configure the open file dialog openFileDialog1.Title = "Add File";

openFileDialog1.Filter = "All Files (*.*)|*.*"; openFileDialog1.FileName = "";

// return if the user cancels the operation

if (openFileDialog1.ShowDialog() == DialogResult.Cancel) {

return; }

// set a local variable to contain the file name  // captured from the open file dialog

string sFilePath;

sFilePath = openFileDialog1.FileName; if (sFilePath == "")

return;

// make sure the file exists before adding  // its path to the list of files to be

 // compressed if (System.IO.File.Exists(sFilePath) == false) return; else txtAddFile.Text = sFilePath; }

The next block of code is used to add a file selected by the previous

method (Browse button) and add to a list of files to included in the

(12)

zipped folder. Again, this section of code is annotated to describe what

each part of the code does.

 /// <summary>

 /// Button click event handler used to add files from the browse  /// textbox to the listbox control

 /// </summary>

 /// <param name="sender"></param>  /// <param name="e"></param>

private void btnAddFile_Click(object sender, EventArgs e) {

// Check for content in the text box if (txtAddFile.Text == string.Empty) {

MessageBox.Show("Use the browse button to search for " +"the file to be added.", "Missing File Name");

return; }

 // Only allow the file to be added if the file is not a duplicate for (int i = 0; i < lstFilePaths.Items.Count; i++)

{

if (lstFilePaths.Items[i].ToString() ==txtAddFile.Text.ToString()) {

MessageBox.Show("That file has already been added to the list.", "Duplicate");

return; }

}

 // Add the file to the listbox list if (txtAddFile.Text != string.Empty)

lstFilePaths.Items.Add(txtAddFile.Text.ToString());

// clear the textbox and move the focus back to the textbox txtAddFile.Text = string.Empty;

txtAddFile.Focus(); }

The next section of code is the Remove button's click event handler;

this method allows the user to remove items from the listbox list after

they have been added using the browse button and add button.

 /// <summary>

 /// Button click handler to remove selected items from  /// the listbox

 /// </summary>

 /// <param name="sender"></param>  /// <param name="e"></param>

private void btnRemoveFile_Click(object sender, EventArgs e) {

try {

lstFilePaths.Items.Remove(lstFilePaths.SelectedItem); }

(13)

catch (Exception ex) {

MessageBox.Show(ex.Message, "Error"); }

}

Next up is a button event handler that uses the Folder Browser Dialog

control to help the user to specify a destination path for the finished

zip file.

 /// <summary>

 /// Button click handler used to set the path to  /// the zipped file

 /// </summary>

 /// <param name="sender"></param>  /// <param name="e"></param>

private void btnSaveBrowse_Click(object sender, EventArgs e) {

 // clear the folder path

txtSaveTo.Text = string.Empty;  // Show the FolderBrowserDialog.

DialogResult result = folderBrowserDialog1.ShowDialog(); if (result == DialogResult.OK)

{

txtSaveTo.Text = folderBrowserDialog1.SelectedPath; }

}

The next button click event handler contains the code used to gather

up the marked files and zip them up the destination folder set. The

code will gather up the identified files, copy the files to a temporary

folder inside the destination folder, zip them up, and then remove the

temporary folder. This code is also annotated and you may review the

notes contained within the code block to read a description of what is

happening at each stage in the progress.

 /// <summary>

 /// Collect the files into a common folder location, zip the  /// files up, and delete the copied files and folder

 /// </summary>

 /// <param name="sender"></param>  /// <param name="e"></param>

private void btnSave_Click(object sender, EventArgs e) {

 // make sure there are files to zip if (lstFilePaths.Items.Count < 1) {

MessageBox.Show("There are not files queued for the zip operation", "Empty File Set");

return; }

(14)

 // make sure there is a destination defined if (txtSaveTo.Text == string.Empty)

{

MessageBox.Show("No destination file has been defined.", "Save To Empty"); return;

}

blUpdate.Visible = true; lblUpdate.Refresh();

 // name the zip file whatever the folder is named  // by splitting the file path to get the folder name

string[] sTemp = txtSaveTo.Text.Split('\\');

string sZipFileName = sTemp[sTemp.Length - 1].ToString();  // check to see if zipped file already exists

 // user may rename it in the text box if it does.

FileInfo fi = new FileInfo(txtSaveTo.Text + "\\" + sZipFileName + ".zip"); if (fi.Exists)

{

 // move it to the folder try

{

StringBuilder sb = new StringBuilder();

sb.Append("The file " + sZipFileName + " already exists."); sb.Append("You may rename it in the save to text box."); MessageBox.Show(sb.ToString(), "Existing File Name"); txtSaveTo.Focus();

return; }

catch {

MessageBox.Show("Rename the file or select a new location.", "File Error");

return; }

}

// Check for the existence of the target folder and  // create it if it does not exist

if (!System.IO.Directory.Exists(txtSaveTo.Text +"\\TempZipFile\\")) {

System.IO.Directory.CreateDirectory(txtSaveTo.Text +"\\TempZipFile\\"); }

 // Set up a string to hold the path to the temp folder

string sTargetFolderPath = (txtSaveTo.Text + "\\TempZipFile\\");  // Process the files and move each into the target folder

for (int i = 0; i < lstFilePaths.Items.Count; i++) {

string filePath = lstFilePaths.Items[i].ToString(); FileInfo fi2 = new FileInfo(filePath);

if (fi2.Exists) {

 // move it to the folder try

(15)

{

fi2.CopyTo(sTargetFolderPath + fi2.Name, true); }

catch {

 // clean up if the operation failed

System.IO.Directory.Delete(sTargetFolderPath);

MessageBox.Show("Could not copy files to temp folder.", "File Error");

return; }

} }

// zip up the files try

{

lblUpdate.Visible = true; lblUpdate.Refresh();

string[] filenames = Directory.GetFiles(sTargetFolderPath);  // Zip up the files - From SharpZipLib Demo Code

using (ZipOutputStream s = new ZipOutputStream(File.Create(txtSaveTo.Text + "\\" +sZipFileName + ".zip")))

{

s.SetLevel(9); // 0-9, 9 being the highest compression byte[] buffer = new byte[4096];

foreach (string file in filenames) {

ZipEntry entry = new

ZipEntry(Path.GetFileName(file)); entry.DateTime = DateTime.Now; s.PutNextEntry(entry);

using (FileStream fs = File.OpenRead(file)) {

int sourceBytes; do

{

sourceBytes = fs.Read(buffer, 0,buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } s.Finish(); s.Close(); }

 // remove the progress bar lblUpdate.Visible = false;

// clean up files by deleting the temp folder and its content

System.IO.Directory.Delete(txtSaveTo.Text + "\\TempZipFile\\", true); // Notify user

(16)

 // empty everything

lstFilePaths.Items.Clear();

txtSaveTo.Text = string.Empty; txtAddFile.Text = string.Empty; }

catch (Exception ex) {

MessageBox.Show(ex.Message.ToString(), "Zip Operation Error"); }

}

The only remaining code in the project is that used to terminate the

application.

 /// <summary>

 /// Exit the application  /// </summary>

 /// <param name="sender"></param>  /// <param name="e"></param>

private void btnExit_Click(object sender, EventArgs e) {

this.Dispose(); }

That wraps up the description of the code used in this project.

Summary:

This example demonstrates zipping up a folder using the SharpZipLib;

in this example, the interface is provided in the form of a stand alone

desktop application. The same approach described in this project could

be applied within the context of a large application that may be

required to gather up multiple files and zip them into a single zipped

folder. As with all things, there are other ways to do this same sort of 

thing, however, given the availability of the SharpZipLib, this is a

relatively simple process.

Search

File Upload & Compression in ASP.Net

(17)

Introduction

In this article I am going to look at how to upload a file to the web server and compress it using the compression methods provided in .Net. I will use the open source compression method to compress to a .gz file. The method is available in System.IO.Compression.

Working the Code: Upload & Compression example

Let us start off by quickly putting together a simple interface for our web-page. The screen shot below shows the screen that I ended up with:

Figure 1.: File upload and compression Web form

Some points to note. The Text-Box followed by the Browse button is the HTML File Upload Control. When you add that to your web page remember to add the RunAt tag in HTML View:

<input id="fileUpload" type="file" runat="server" /> This will allow us to work with the control from the server.

Let us get to the code side. Double-click on the Upload Button to create an event-handler. For this button, we want to simply upload the file, without compressing it. Make sure to import System.IO and System.IO.Compression at the top for  we'll be using both in the code, and its better not to type System.IO every time one needs to call it.

Here is the piece of code that you'd want to include behind this button: If fileUpload.PostedFile Is Nothing Then

Me.lblResult.Text = "No File Selected to Upload." Exit Sub

End If 

'Retrieve file information and upload to server. Dim strName As String

strName = System.IO.Path.GetFileName(fileUpload.PostedFile.FileName) Try

fileUpload.PostedFile.SaveAs(Server.MapPath(strName))

Me.lblResult.Text = """" + strName + """ was uploaded successfully." Catch ex As Exception

Me.lblResult.Text = "An Error Occured While Uploading File." End Try

What we are doing here is that we read the PostedFile from the HTML control, and save it to our server using Server.MapPath to get our desired destination. That being a simple method let us now look into compression. In the second button's event handler, start off the same way as we did in the first, by checking if the user posted a file or no t. Then proceed to the following:

(18)

'A String object reads the file name (locally)

Dim strName As String = Path.GetFileName(fileUpload.PostedFile.FileName) 'Create a stream object to read the file.

Dim myStream As Stream = fileUpload.PostedFile.InputStream 'Allocate space in buffer for use according to length of file. Dim myBuffer(myStream.Length) As Byte

'Read the file using the Stream object and fill the buffer. myStream.Read(myBuffer, 0, myBuffer.Length)

myStream.Close()

'Change the extension of the file creating a FileStream object. Dim myCompressedFile As FileStream

myCompressedFile = File.Create( _ 

Server.MapPath(Path.ChangeExtension(strName,"gz"))) 'GZip object that compress the file

Dim myStreamZip As New GZipStream(myCompressedFile, CompressionMode.Compress) 'Write Back

myStreamZip.Write(myBuffer, 0, myBuffer.Length) myStreamZip.Close()

Me.lblResult.Text = """" + strName lblResult.Text = lblResult.Text + " was compressed &uploaded successfully." What we do here is read the file into a stream, change its extension to the appropriate GZ ext, and compress using the GZipStream compression method. The same method, GZipStream, can be used for UnCompressing files, by using CompressionMode.UnCompress. Don't forget to download Sample Visual Studio .NET 2005 project for this tutorial here .

References

Related documents

Calculations for lateral loads on piles are based on the “Pressuremeter Theory” which in simple form assumes that the pile in this case acts like a beam with the H-force acting at

Previous work has shown reductions in negative priming effects in older adults, which has been taken as evidence of impaired perceptual inhibition ( Hasher et al., 1991 ;

Sebagian besar objek penelitian dari sektor bisnis di sini tidak memiliki pola pikir yang mengarah kelestarian lingkungan secara langsung, sektor bisnis pada

O ensino de programação pode ser utilizado para trabalhar o PC no contexto escolar como uma maneira de estimular o desenvolvimento do raciocínio lógico no aluno e

In the case of URM buildings, for all school categories and all seismic hazard relationships, when the fragility curves are based on the assumption of intermediate and upper bounds

Research based on historical evidence allows a number of generalizations as to patterns of advances in productivity and economic growth, including the importance of economic

‘Onslaught’ drifts through sylvan surroundings past Norden Heath crossing, bridge 13, and Woodpecker Siding on preview day, 5th May, with the only return service to travel the full