How to extract a folder from zip file using SharpZipLib? - c#

I have a test.zip file which contains inside a Folder with a bunch of other files and folders in it.
I found SharpZipLib after figuring out that .gz / GzipStream was not the way to go since its only for individual files. More importantly, doing this is similar to using GZipStream meaning it will create a FILE. But I have whole folder zipped. How do I unzip to a
For some reason the example unzipping here is set to ignore directories, so I'm not totally sure how that is done.
Also, I need to use .NET 2.0 for accomplish this.

I think it is the easier way.
Default functionality (please look here for more info https://github.com/icsharpcode/SharpZipLib/wiki/FastZip)
it extract with folders.
code:
using System;
using ICSharpCode.SharpZipLib.Zip;
var zipFileName = #"T:\Temp\Libs\SharpZipLib_0860_Bin.zip";
var targetDir = #"T:\Temp\Libs\unpack";
FastZip fastZip = new FastZip();
string fileFilter = null;
// Will always overwrite if target filenames already exist
fastZip.ExtractZip(zipFileName, targetDir, fileFilter);

This is how I did it:
public void UnZipp(string srcDirPath, string destDirPath)
{
ZipInputStream zipIn = null;
FileStream streamWriter = null;
try
{
Directory.CreateDirectory(Path.GetDirectoryName(destDirPath));
zipIn = new ZipInputStream(File.OpenRead(srcDirPath));
ZipEntry entry;
while ((entry = zipIn.GetNextEntry()) != null)
{
string dirPath = Path.GetDirectoryName(destDirPath + entry.Name);
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
if (!entry.IsDirectory)
{
streamWriter = File.Create(destDirPath + entry.Name);
int size = 2048;
byte[] buffer = new byte[size];
while ((size = zipIn.Read(buffer, 0, buffer.Length)) > 0)
{
streamWriter.Write(buffer, 0, size);
}
}
streamWriter.Close();
}
}
catch (System.Threading.ThreadAbortException lException)
{
// do nothing
}
catch (Exception ex)
{
throw (ex);
}
finally
{
if (zipIn != null)
{
zipIn.Close();
}
if (streamWriter != null)
{
streamWriter.Close();
}
}
}
It's sloppy but I hope it helps!

Related

Stream was not writeable (StreamWriter)

I'm trying to remove specific line from file on IsolatedStorage but I'm still receiving the "Stream was not writeable" from following method:
public async static void RemoveFavoriteFromFile(int id)
{
string favoriteFilename = Globals.FavoriteFilepath;
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var folder = await local.GetFolderAsync("DataFolder");
var file = await folder.OpenStreamForReadAsync(Globals.FavoriteFilepath);
using (StreamReader sr = new StreamReader(file))
{
using (StreamWriter sw = new StreamWriter(file))
{
string line = null;
while ((line = sr.ReadLine()) != null)
{
if (String.Compare(line, id.ToString()) == 0)
continue;
sw.WriteLine(line);
}
}
}
}
on line using (StreamWriter sw = new StreamWriter(file))
Could anybody help me please?
Thanks in advance
EDIT: I would mainly ask you to advice me how to remove specific line from existing file, no matter what I created already. Main issue for me in meaning of understanding is that how to write/edit a file which I firstly need to read for finding the specific line.
Reading and writing to the same file at the same time is always a bad idea.
Either write to a swap file "filename_swap.txt". After it has finished writing the entire file, delete the original file and rename the "filename_swap.txt" to the original file (basically replacing it).
Or you can read the entire file into a buffer, close the file. Make your changes to said buffer then open the file again for writing. This time, write the entire content of the modified buffer.
So lets modularize your program
using System.Threading.Tasks;
// read the specific file into a string buffer
private async Task<string> ReadFileIntoBuffer(string fileName)
{
string buffer = ""; // our buffer
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; // local folder
var folder = await local.GetFolderAsync("DataFolder"); // sub folder
// open the file for reading
using (Stream s = await folder.OpenStreamForReadAsync(fileName))
{
using (StreamReader sr = new StreamReader(s))
{
buffer = await sr.ReadToEndAsync();
}
}
// return the buffer
return buffer;
}
// write the string buffer to a specific file
private async Task<bool> WriteBufferToFile(string fileName, string buffer)
{
try
{
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; // local folder
var folder = await local.GetFolderAsync("DataFolder"); // sub folder
// open the file for writing
using (Stream s = await folder.OpenStreamForWriteAsync(fileName, CreationCollisionOption.ReplaceExisting))
{
using (StreamWriter sw = new StreamWriter(s))
{
await sw.WriteAsync(buffer);
}
}
}
catch (Exception ex)
{
string error_message = ex.Message;
return false;
}
return true;
}
// New Delete Lines function based off your old one
private string DeleteLines(string input_buffer, int id)
{
string output_buffer = "";
using (StringReader sr = new StringReader(input_buffer))
{
while (true)
{
string line = sr.ReadLine();
if (line != null)
{
if (String.Compare(line, id.ToString()) == 0)
{
}
else
{
// add it to the output_buffer plus the newline
output_buffer += (line + "\n");
}
}
else
{
break;
}
}
}
return output_buffer;
}
If you have trouble understanding a problem it generally a good idea to break it into smaller parts and debug from there.

Deletion of compressed file after extracting it with nunrar

I used the lib Nunrar site to extract a .rar file:
RarArchive.WriteToDirectory(fs.Name, Path.Combine(#"D:\DataDownloadCenter", path2), ExtractOptions.Overwrite);
the decompression works fine, but I can't after this operation of extract delete the original compressed file
System.IO.File.Delete(path);
because the file is is used by another process
the hole function :
try
{
FileStream fs = File.OpenRead(path);
if(path.Contains(".rar")){
try
{
RarArchive.WriteToDirectory(fs.Name, Path.Combine(#"D:\DataDownloadCenter", path2), ExtractOptions.Overwrite);
fs.Close();
}
catch { }
}
catch { return; }
finally
{
if (zf != null)
{
zf.IsStreamOwner = true; // Makes close also shut the underlying stream
zf.Close(); // Ensure we release resources
}
}
try
{
System.IO.File.Delete(path);
}
catch { }
So can I delete the compressed file after extract it?
I don't know what zf is but you can also likely wrap that in a using statement. Try replacing your FileStream fs part with this
using( FileStream fs = File.OpenRead(path))
{
if(path.Contains(".rar"))
{
try
{
RarArchive.WriteToDirectory(fs.Name, Path.Combine(#"D:\DataDownloadCenter", path2), ExtractOptions.Overwrite);
}
catch { }
}
}
This way fs is closed even if path doesn't contain .rar. You're only closing the fs if rar exists within the filename.
Also, does the library have its own stream handling? It could have a method that closes it.
I also had this issue with nunrar, nether close() or a using statement seem to fix this.
unfortunately the Documentation is scarce, so im now using the SharpCompress library it is a fork of the nunrar library according to the devs of nunrar.The documentation on SharpCompress is also scarce (but less) so here is my method im using:
private static bool unrar(string filename)
{
bool error = false;
string outputpath = Path.GetDirectoryName(filename);
try
{
using (Stream stream = File.OpenRead(filename))
{
var reader = ReaderFactory.Open(stream);
while (reader.MoveToNextEntry())
{
if (!reader.Entry.IsDirectory)
{
Console.WriteLine(reader.Entry.Key);
reader.WriteEntryToDirectory(outputpath, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true });
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Failed: " + e.Message);
error = true;
}
if (!error)
{
File.Delete(filename);
}
return error;
}
Add the following libraries to the top
using SharpCompress.Common;
using SharpCompress.Readers;
Install using nuget.This method works for SharpCompress v0.22.0(latest at the time of writing)

.Net Zip Up files

Whats the best way to zip up files using C#? Ideally I want to be able to seperate files into a single archive.
You can use DotNetZip to archieve this. It´s free to use in any application.
Here´s some sample code:
try
{
// for easy disposal
using (ZipFile zip = new ZipFile())
{
// add this map file into the "images" directory in the zip archive
zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
// add the report into a different directory in the archive
zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
zip.AddFile("ReadMe.txt");
zip.Save("MyZipFile.zip");
}
}
catch (System.Exception ex1)
{
System.Console.Error.WriteLine("exception: " + ex1);
}
This is now built into the framework if you have version 4.5+
Otherwise, use Ionic.
Namespace is System.IO.Packaging.ZIPPackage.
See http://visualstudiomagazine.com/articles/2012/05/21/net-framework-gets-zip.aspx for a story.
Have you looked at SharpZipLib?
I believe you can build zip files with classes in the System.IO.Packaging namespace - but every time I've tried to look into it, I've found it rather confusing...
Take a look at this library:
http://www.icsharpcode.net/OpenSource/SharpZipLib/
It is pretty comprehensive, it deals with many formats, is open-source, and you can use in closed-source commercial applications.
It is very simple to use:
byte[] data1 = new byte[...];
byte[] data2 = new byte[...];
/*...*/
var path = #"c:\test.zip";
var zip = new ZipOutputStream(new FileStream(path, FileMode.Create))
{
IsStreamOwner = true
}
zip.PutNextEntry("File1.txt");
zip.Write(data1, 0, data1.Length);
zip.PutNextEntry("File2.txt");
zip.Write(data2, 0, data2.Length);
zip.Close();
zip.Dispose();
There are a few librarys around - the most popular of which are DotNetZip and SharpZipLib.
Hi i created two methods with the ShapLib library (you can download it here http://www.icsharpcode.net/opensource/sharpziplib/) that would like to share, they are very easy to use just pass source and target path (fullpath including folder/file and extension). Hope it help you!
//ALLYOURNAMESPACESHERE
using ...
//SHARPLIB
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
public static class FileUtils
{
/// <summary>
///
/// </summary>
/// <param name="sourcePath"></param>
/// <param name="targetPath"></param>
public static void ZipFile(string sourcePath, string targetPath)
{
string tempZipFilePath = targetPath;
using (FileStream tempFileStream = File.Create(tempZipFilePath, 1024))
{
using (ZipOutputStream zipOutput = new ZipOutputStream(tempFileStream))
{
// Zip with highest compression.
zipOutput.SetLevel(9);
DirectoryInfo directory = new DirectoryInfo(sourcePath);
foreach (System.IO.FileInfo file in directory.GetFiles())
{
// Get local path and create stream to it.
String localFilename = file.FullName;
//ignore directories or folders
//ignore Thumbs.db file since this probably will throw an exception
//another process could be using it. e.g: Explorer.exe windows process
if (!file.Name.Contains("Thumbs") && !Directory.Exists(localFilename))
{
using (FileStream fileStream = new FileStream(localFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
// Read full stream to in-memory buffer.
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
// Create a new entry for the current file.
ZipEntry entry = new ZipEntry(file.Name);
entry.DateTime = DateTime.Now;
// set Size and the crc, because the information
// about the size and crc should be stored in the header
// if it is not set it is automatically written in the footer.
// (in this case size == crc == -1 in the header)
// Some ZIP programs have problems with zip files that don't store
// the size and crc in the header.
entry.Size = fileStream.Length;
fileStream.Close();
// Update entry and write to zip stream.
zipOutput.PutNextEntry(entry);
zipOutput.Write(buffer, 0, buffer.Length);
// Get rid of the buffer, because this
// is a huge impact on the memory usage.
buffer = null;
}
}
}
// Finalize the zip output.
zipOutput.Finish();
// Flushes the create and close.
zipOutput.Flush();
zipOutput.Close();
}
}
}
public static void unZipFile(string sourcePath, string targetPath)
{
if (!Directory.Exists(targetPath))
Directory.CreateDirectory(targetPath);
using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
if (theEntry.Name != String.Empty)
{
using (FileStream streamWriter = File.Create(targetPath + "\\" + theEntry.Name))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
}
}
}

recommend a library/API to unzip file in C# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
Looks like no built-in Library/API in C# to unzip a zip file. I am looking for a free (better open source) library/API which could work with .Net 3.5 + VSTS 2008 + C# to unzip a zip file and extract all files into a specific folder.
Any recommended library/API or samples?
The GPL
http://www.icsharpcode.net/OpenSource/SharpZipLib/
OR the less restrictive Ms-PL
http://www.codeplex.com/DotNetZip
To complete this answer the .net framework has ZipPackage I had less success with it.
If all you want to do is unzip the contents of a file to a folder, and you know you'll only be running on Windows, you can use the Windows Shell object. I've used dynamic from Framework 4.0 in this example, but you can achieve the same results using Type.InvokeMember.
dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
dynamic compressedFolderContents = shellApplication.NameSpace(sourceFile).Items;
dynamic destinationFolder = shellApplication.NameSpace(destinationPath);
destinationFolder.CopyHere(compressedFolderContents);
You can use FILEOP_FLAGS to control behaviour of the CopyHere method.
DotNetZip is easy to use. Here's an unzip sample
using (var zip = Ionic.Zip.ZipFile.Read("archive.zip"))
{
zip.ExtractAll("unpack-directory");
}
If you have more complex needs, like you want to pick-and-choose which entries to extract, or if there are passwords, or if you want to control the pathnames of the extracted files, or etc etc etc, there are lots of options. Check the help file for more examples.
DotNetZip is free and open source.
In the past, I've used DotNetZip (MS-PL), SharpZipLib (GPL), and the 7ZIP SDK for C# (public domain). They all work great, and are open source.
I would choose DotNetZip in this situation, and here's some sample code from the C# Examples page:
using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
foreach (ZipEntry e in zip)
{
e.Extract(TargetDirectory);
}
}
SharpZipLib
http://www.icsharpcode.net/OpenSource/SharpZipLib/
Have a look to my small library: https://github.com/jaime-olivares/zipstorer
If you want to use 7-zip compression, check out Peter Bromberg's EggheadCafe article. Beware: the LZMA source code for c# has no xml comments (actually, very few comments at all).
If you do not want to use an external component, here is some code I developed last night using .NET's ZipPackage class.
private static void Unzip()
{
var zipFilePath = "c:\\myfile.zip";
var tempFolderPath = "c:\\unzipped";
using (Package pkg = ZipPackage.Open(zipFilePath, FileMode.Open, FileAccess.Read))
{
foreach (PackagePart part in pkg.GetParts())
{
var target = Path.GetFullPath(Path.Combine(tempFolderPath, part.Uri.OriginalString.TrimStart('/')));
var targetDir = target.Remove(target.LastIndexOf('\\'));
if (!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read))
{
CopyStream(source, File.OpenWrite(target));
}
}
}
}
private static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[4096];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
Things to note:
The ZIP archive MUST have a [Content_Types].xml file in its root. This was a non-issue for my requirements as I will control the zipping of any ZIP files that get extracted through this code. For more information on the [Content_Types].xml file, please refer to: http://msdn.microsoft.com/en-us/magazine/cc163372.aspx There is an example file below Figure 13 of the article.
I have not tested the CopyStream method to ensure it behaves correctly, as I originally developed this for .NET 4.0 using the Stream.CopyTo() method.
#region CreateZipFile
public void StartZip(string directory, string zipfile_path)
{
Label1.Text = "Please wait, taking backup";
#region Taking files from root Folder
string[] filenames = Directory.GetFiles(directory);
// path which the zip file built in
ZipOutputStream p = new ZipOutputStream(File.Create(zipfile_path));
foreach (string filename in filenames)
{
FileStream fs = File.OpenRead(filename);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(filename);
p.PutNextEntry(entry);
p.Write(buffer, 0 , buffer.Length);
fs.Close();
}
#endregion
string dirName= string.Empty;
#region Taking folders from root folder
DirectoryInfo[] DI = new DirectoryInfo(directory).GetDirectories("*.*", SearchOption.AllDirectories);
foreach (DirectoryInfo D1 in DI)
{
// the directory you need to zip
filenames = Directory.GetFiles(D1.FullName);
if (D1.ToString() == "backup")
{
filenames = null;
continue;
}
if (dirName == string.Empty)
{
if (D1.ToString() == "updates" || (D1.Parent).ToString() == "updates" || (D1.Parent).Parent.ToString() == "updates" || ((D1.Parent).Parent).Parent.ToString() == "updates" || (((D1.Parent).Parent).Parent).ToString() == "updates" || ((((D1.Parent).Parent).Parent)).ToString() == "updates")
{
dirName = D1.ToString();
filenames = null;
continue;
}
}
else
{
if (D1.ToString() == dirName) ;
}
foreach (string filename in filenames)
{
FileStream fs = File.OpenRead(filename);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(filename);
p.PutNextEntry(entry);
p.Write(buffer, 0, buffer.Length);
fs.Close();
}
filenames = null;
}
p.SetLevel(5);
p.Finish();
p.Close();
#endregion
}
#endregion
#region EXTRACT THE ZIP FILE
public bool UnZipFile(string InputPathOfZipFile, string FileName)
{
bool ret = true;
Label1.Text = "Please wait, extracting downloaded file";
string zipDirectory = string.Empty;
try
{
#region If Folder already exist Delete it
if (Directory.Exists(Server.MapPath("~/updates/" + FileName))) // server data field
{
String[] files = Directory.GetFiles(Server.MapPath("~/updates/" + FileName));//server data field
foreach (var file in files)
File.Delete(file);
Directory.Delete(Server.MapPath("~/updates/" + FileName), true);//server data field
}
#endregion
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 directoryName = theEntry.Name.Substring(theEntry.Name.IndexOf(FileName)); // server data field
string[] DirectorySplit = directoryName.Split('\\');
for (int i = 0; i < DirectorySplit.Length - 1; i++)
{
if (zipDirectory != null || zipDirectory != "")
zipDirectory = zipDirectory + #"\" + DirectorySplit[i];
else
zipDirectory = zipDirectory + DirectorySplit[i];
}
string first = Server.MapPath("~/updates") + #"\" + zipDirectory;
if (!Directory.Exists(first))
Directory.CreateDirectory(first);
string strNewFile = #"" + baseDirectory + #"\" + directoryName;
if (File.Exists(strNewFile))
{
continue;
}
zipDirectory = string.Empty;
using (FileStream streamWriter = File.Create(strNewFile))
{
int size = 2048;
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(strNewDirectory);
}
}
}
ZipStream.Close();
}
}
}
catch (Exception ex)
{
ret = false;
}
return ret;
}
#endregion
I would recommend our http://www.rebex.net/zip.net/ but I'm biased. Download trial and check the features and samples yourself.
SevenZipSharp is a wrapper around tha 7z.dll and LZMA SDK, which is Open-source, and free.
SevenZipCompressor compressor = new SevenZipCompressor();
compressor.CompressionLevel = CompressionLevel.Ultra;
compressor.CompressionMethod = CompressionMethod.Lzma;
compressor.CompressionMode = CompressionMode.Create;
compressor.CompressFiles(...);

Unzipping a file error

I am using the SharpZipLib open source .net library from www.icsharpcode.net
My goal is to unzip an xml file and read it into a dataset. However I get the following error reading the file into a dataset: "Data at the root level is invalid. Line 1, position 1."
I believe what is happening is the unzipping code is not releasing the file for the following reasons.
1.) If I unzip the file and exit the application. When I restart the app I CAN read the unzipped file into a dataset.
2.) If I read in the xml file right after writing it out (no zipping) then it works fine.
3.) If I write the dataset to xml, zip it up, unzip it, then attempt to read it back in I get the exception.
The code below is pretty straight forward. UnZipFile will return the name of the file just unzipped. Right below this call is the call to read it into a dataset. The variable fileToRead is the full path to the newly unzipped xml file.
string fileToRead = UnZipFile(filepath, DOViewerUploadStoreArea);
ds.ReadXml(fileToRead )
private string UnZipFile(string file, string dirToUnzipTo)
{
string unzippedfile = "";
try
{
ZipInputStream s = new ZipInputStream(File.OpenRead(file));
ZipEntry myEntry;
string tmpEntry = String.Empty;
while ((myEntry = s.GetNextEntry()) != null)
{
string directoryName = dirToUnzipTo;
string fileName = Path.GetFileName(myEntry.Name);
string fileWDir = directoryName + fileName;
unzippedfile = fileWDir;
FileStream streamWriter = File.Create(fileWDir);
int size = 4096;
byte[] data = new byte[4096];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0) { streamWriter.Write(data, 0, size); }
else { break; }
}
streamWriter.Close();
}
s.Close();
}
catch (Exception ex)
{
LogStatus.WriteErrorLog(ex, "ERROR", "DOViewer.UnZipFile");
}
return (unzippedfile);
}
Well, what does the final file look like? (compared to the original). You don't show the zipping code, which might be part of the puzzle, especially as you are partially swallowing the exception.
I would also try ensuring everything IDisposable is Dispose()d, ideally via using; also - in case the problem is with path construction, use Path.Combine. And note that if myEntry.Name contains sub-directories, you will need to create them manually.
Here's what I have - it works for unzipping ICSharpCode.SharpZipLib.dll:
private string UnZipFile(string file, string dirToUnzipTo)
{
string unzippedfile = "";
try
{
using(Stream inStream = File.OpenRead(file))
using (ZipInputStream s = new ZipInputStream(inStream))
{
ZipEntry myEntry;
byte[] data = new byte[4096];
while ((myEntry = s.GetNextEntry()) != null)
{
string fileWDir = Path.Combine(dirToUnzipTo, myEntry.Name);
string dir = Path.GetDirectoryName(fileWDir);
// note only supports a single level of sub-directories...
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
unzippedfile = fileWDir; // note; returns last file if multiple
using (FileStream outStream = File.Create(fileWDir))
{
int size;
while ((size = s.Read(data, 0, data.Length)) > 0)
{
outStream.Write(data, 0, size);
}
outStream.Close();
}
}
s.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return (unzippedfile);
}
It could also be that the problem is either in the code that writes the zip, or the code that reads the generated file.
I compared the original with the final using TextPad and they are identical.
Also I rewrote the code to take advantage of the using. Here is the code.
My issue seems to be centered around file locking or something. If I unzip the file quit the application then start it up it will read find.
private string UnZipFile(string file, string dirToUnzipTo)
{
string unzippedfile = "";
try
{
using (ZipInputStream s = new ZipInputStream(File.OpenRead(file)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = dirToUnzipTo;
string fileName = Path.GetFileName(theEntry.Name);
string fileWDir = directoryName + fileName;
unzippedfile = fileWDir;
if (fileName != String.Empty)
{
using (FileStream streamWriter = File.Create(fileWDir))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
}
}
catch (Exception ex)
{
LogStatus.WriteErrorLog(ex, "ERROR", "DOViewer.UnZipFile");
}
return (unzippedfile);
}
This is a lot simpler to do with DotNetZip.
using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
zip.ExtractAll(TargetDirectory);
}
If you want to decide on which files to extract ....
using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
foreach (ZipEntry e in zip)
{
if (wantThisFile(e.FileName)) e.Extract(TargetDirectory);
}
}
If you would like to overwrite existing files during extraction:
using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
zip.ExtractAll(TargetDirectory, ExtractExistingFileAction.OverwriteSilently);
}
Or, to extract password-protected entries:
using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
zip.Password = "Shhhh, Very Secret!";
zip.ExtractAll(TargetDirectory, ExtractExistingFileAction.OverwriteSilently);
}

Categories

Resources