Hi this code is working for me but it is unzipping the files into the same directory. I want to unzip the files to a new directory. See code below
public void Main()
{
DirectoryInfo directorySelected = new DirectoryInfo(m_ProjectPath+m_Tool);
foreach (FileInfo fileToDecompress in directorySelected.GetFiles("*.gz"))
{
Decompress(fileToDecompress);
}
}
public void Decompress(FileInfo fileToDecompress)
{
using (FileStream originalFileStream = fileToDecompress.OpenRead())
{
string currentFileName = fileToDecompress.FullName;
string newFileName = currentFileName.Remove(
currentFileName.Length - fileToDecompress.Extension.Length);
using (FileStream decompressedFileStream = File.Create(newFileName))
{
using (GZipStream decompressionStream =
new GZipStream(originalFileStream, CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
}
}
}
}
You're copying the decompressedFileStream to newFileName which is:
string newFileName = currentFileName.Remove(
currentFileName.Length - fileToDecompress.Extension.Length);
Look at newFileName in your debugger; it's just the original file name, in the original directory, with the filename extension removed. If you want to copy it to a different directory you have to specify the directory, not copy the one from currentFileName. You want to know how to specify a directory? That will depend if you have a command-line application, a WinForm, WPF, ASP.NET, or Windows Store app.
Related
using Ionic.Zip;
var savedzipFile = "C:\alldocs\issues\issuesfromtoday.zip";
var selectedfolderfromDialog = "D:\MyDocs";
This is what I have. I cant use webblient because its not a url. How to I save the zip file to that selected folder location? Zip file has PDFs if that matters.
This should do the trick:
var savedzipFile = #"C:\alldocs\issues\issuesfromtoday.zip";
var selectedfolderfromDialog = #"D:\MyDocs";
using (var sourceStream = System.IO.File.Open(savedzipFile, System.IO.FileMode.Open))
{
using (var targetStream = System.IO.File.OpenWrite(selectedfolderfromDialog + #"\" + savedzipFile.Substring(savedzipFile.LastIndexOf('\\'))))
{
sourceStream.CopyTo(targetStream);
}
}
I wanted to save the unzipped file to a folder in IsolatedStorage. I have read the file zip file from IsolatedStorage and now want to unzip them into a folder. i have tried this way :-
private async Task UnZipFile(string fileName)
{
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.ReadWrite))
{
UnZipper unzip = new UnZipper(fileStream);
var filename = unzip.FileNamesInZip.FirstOrDefault();
if (filename != null)
{
// i can have the stream too. like this.
// var zipStream = unzip.GetFileStream(filename)
// here i am not getting how to save unzip file to a folder.
}
}
Here is what i got :) Hope it will help somebody.
private async Task UnZipFile()
{
// you can use Isolated storage too
var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (var fileStream = Application.GetResourceStream(new Uri("sample.zip", UriKind.Relative)).Stream)
{
var unzip = new UnZipper(fileStream);
foreach (string filename in unzip.FileNamesInZip)
{
if (!string.IsNullOrEmpty(filename))
{
if (filename.Any(m => m.Equals('/')))
{
myIsolatedStorage.CreateDirectory(filename.Substring(0, filename.LastIndexOfAny(new char[] { '/' })));
}
//save file entry to storage
using (var streamWriter =
new StreamWriter(new IsolatedStorageFileStream(filename,
FileMode.Create,
FileAccess.ReadWrite,
myIsolatedStorage)))
{
streamWriter.Write(unzip.GetFileStream(filename));
}
}
}
}
}
Inside my app, I am trying to download about 180 small audio files all at once. I tried the BackgroundTransferService, but it does not seem stable with so many small files. So, now I am downloading a ZIP of all those audio and want extract them in "audio" folder. I tried the method in this thread:
How to unzip files in Windows Phone 8
But I get this error: 'System.IO.IOException' occurred in mscorlib.ni.dll... in the following code. How can I overcome this issue?
while (reader.ReadInt32() != 101010256)
{
reader.BaseStream.Seek(-5, SeekOrigin.Current); // this line causes error
}...
Also, where do I need to place this code and where do I give it the destination directory?
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(#"audio.rar", FileMode.Open, FileAccess.ReadWrite))
{
UnZipper unzip = new UnZipper(fileStream);
foreach (string filename in unzip.FileNamesInZip())
{
string FileName = filename;
}
}
Use Silverlight SharpZipLib. Add SharpZipLib.WindowsPhone7.dll to your project (works on WP8 silverlight also).
private void Unzip()
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
ZipEntry entry;
int size;
byte[] data = new byte[2048];
using (ZipInputStream zip = new ZipInputStream(store.OpenFile("YourZipFile.zip", FileMode.Open)))
{
// retrieve each file/folder
while ((entry = zip.GetNextEntry()) != null)
{
if (!entry.IsFile)
continue;
// if file name is music/rock/new.mp3, we need only new.mp3
// also you must make sure file name doesn't have unsupported chars like /,\,etc.
int index = entry.Name.LastIndexOf('/');
string name = entry.Name.Substring(index + 1);
// create file in isolated storage
using (var writer = store.OpenFile(name, FileMode.Create))
{
while (true)
{
size = zip.Read(data, 0, data.Length);
if (size > 0)
writer.Write(data, 0, size);
else
break;
}
}
}
}
}
}
There are several 3rd party libraries in order to extract ZIP files in WP8 like the ZipLib which you can download from # http://slsharpziplib.codeplex.com/
however DotNetZip a parent ZipLib and much more stable.
Here is a sample code. Not checked if it works, but this is how you go at it.
ZipFile zip = ZipFile.Read(ZipFileToUnzip);
foreach (ZipEntry ent in zip)
{
ent.Extract(DirectoryWhereToUnizp, ExtractExistingFileAction.OverwriteSilently);
}
I have just solved this. what you can do is use this method and your file will go save to isolated storage in proper folder structure as present in your zip file. you can change according to your need where you want to store the data.
I have just read a sample.zip file. From your app folder.
private async Task UnZipFile()
{
var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (var fileStream = Application.GetResourceStream(new Uri("sample.zip", UriKind.Relative)).Stream)
{
var unzip = new UnZipper(fileStream);
foreach (string filename in unzip.FileNamesInZip)
{
if (!string.IsNullOrEmpty(filename))
{
if (filename.Any(m => m.Equals('/')))
{
myIsolatedStorage.CreateDirectory(filename.Substring(0, filename.LastIndexOfAny(new char[] { '/' })));
}
//save file entry to storage
using (var streamWriter =
new StreamWriter(new IsolatedStorageFileStream(filename,
FileMode.Create,
FileAccess.ReadWrite,
myIsolatedStorage)))
{
streamWriter.Write(unzip.GetFileStream(filename));
}
}
}
}
}
cheers :)
I want compress/decompress directories without any dll.
I use this code for compress a file with GzipStream.
public static void Compress(FileInfo fileToCompress)
{
using (FileStream originalFileStream = fileToCompress.OpenRead())
{
if ((File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
{
using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fileToCompress.Name, fileToCompress.Length.ToString(), compressedFileStream.Length.ToString());
}
}
}
}
}
I use this link for compress directory. but don't work for me :(
From what I can tell, you can't compress an entire directory to a single gz file. You end up with multiple gz files.
You can package the directory up as a .Tar file and then use gZip on the tar file.
Which would require using a library such as SharpZipLib. You can install the library from the Manage NuGet Packages menu.
DirectoryInfo directoryOfFilesToBeTarred = new DirectoryInfo(#"c:\tar\start");
FileInfo[] filesInDirectory = directoryOfFilesToBeTarred.GetFiles();
String tarArchiveName = #"c:\tar\mytararchive.tar.gz";
using (Stream targetStream = new GZipOutputStream(File.Create(tarArchiveName)))
{
using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(targetStream, TarBuffer.DefaultBlockFactor))
{
foreach (FileInfo fileToBeTarred in filesInDirectory)
{
TarEntry entry = TarEntry.CreateEntryFromFile(fileToBeTarred.FullName);
tarArchive.WriteEntry(entry, true);
}
}
}
Source:
https://dotnetcodr.com/2015/02/04/packing-and-unpacking-files-using-tar-archives-in-net/
OR
You can zip the directory in pure .NET 3.0. Using SharpZipLib may not be desirable due to the modified GPL license.
First, you will need a reference to WindowsBase.dll.
This code will open or create a zip file, create a directory inside, and place the file in that directory. If you want to zip a folder, possibly containing sub-directories, you could loop through the files in the directory and call this method for each file. Then, you could depth-first search the sub-directories for files, call the method for each of those and pass in the path to create that hierarchy within the zip file.
public void AddFileToZip(string zipFilename, string fileToAdd, string destDir)
{
using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
{
string destFilename = "." + destDir + "\\" + Path.GetFileName(fileToAdd);
Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
if (zip.PartExists(uri))
{
zip.DeletePart(uri);
}
PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
{
using (Stream dest = part.GetStream())
{
CopyStream(fileStream, dest);
}
}
}
}
destDir could be an empty string, which would place the file directly in the zip.
Sources:
https://weblogs.asp.net/jongalloway/creating-zip-archives-in-net-without-an-external-library-like-sharpziplib
https://weblogs.asp.net/albertpascual/creating-a-folder-inside-the-zip-file-with-system-io-packaging
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
recommend a library/API to unzip file in C#
deal all plz suggest the ways to unzip file to selected folder using c#
Have a look at the GZipStream, it's one of the built-in zip support in the framework, there's an example on the MSDN page:
http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx
Here's the example from the MSDN page:
public class Program
{
public static void Main()
{
// Path to directory of files to compress and decompress.
string dirpath = #"c:\users\public\reports";
DirectoryInfo di = new DirectoryInfo(dirpath);
// Compress the directory's files.
foreach (FileInfo fi in di.GetFiles())
{
Compress(fi);
}
// Decompress all *.gz files in the directory.
foreach (FileInfo fi in di.GetFiles("*.gz"))
{
Decompress(fi);
}
}
public static void Compress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Prevent compressing hidden and
// already compressed files.
if ((File.GetAttributes(fi.FullName)
& FileAttributes.Hidden)
!= FileAttributes.Hidden & fi.Extension != ".gz")
{
// Create the compressed file.
using (FileStream outFile =
File.Create(fi.FullName + ".gz"))
{
using (GZipStream Compress =
new GZipStream(outFile,
CompressionMode.Compress))
{
// Copy the source file into
// the compression stream.
inFile.CopyTo(Compress);
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fi.Name, fi.Length.ToString(), outFile.Length.ToString());
}
}
}
}
}
public static void Decompress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Get original file extension, for example
// "doc" from report.doc.gz.
string curFile = fi.FullName;
string origName = curFile.Remove(curFile.Length -
fi.Extension.Length);
//Create the decompressed file.
using (FileStream outFile = File.Create(origName))
{
using (GZipStream Decompress = new GZipStream(inFile,
CompressionMode.Decompress))
{
// Copy the decompression stream
// into the output file.
Decompress.CopyTo(outFile);
Console.WriteLine("Decompressed: {0}", fi.Name);
}
}
}
}
}
You have two options,
1) You can use the a 3rd party API, like DotNetZip (http://www.codeplex.com/DotNetZip)
2) Or you can use System.IO.Compression.DeflateStream. It requires .NET 2.0.
Try to use FastZip to zip and unzip the files
In .NET there are two built-in ways to work with compressed streams. DeflateStream and GZipStream
DeflateStream ds = new DeflateStream(File.OpenRead(#"c:\myfolder\data.zip"), CompressionMode.Decompress);
GZipStream gZip = new GZipStream(File.OpenRead(#"c:\myfolder\data.zip"), CompressionMode.Decompress);