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
Related
I have issue when action open file follow format .gz/.tar.gz
This is image error
This is code:
public void Check(string path)
{
foreach (var fileName in Directory.GetFiles(path))
{
if (Path.GetExtension(fileName) == ".gz" && Path.GetFileNameWithoutExtension(fileName).Contains("tar"))
{
Console.WriteLine(fileName);
ExtractTGZ(fileName, Path.GetDirectoryName(fileName) + #"\" + Path.GetFileNameWithoutExtension(fileName));
System.IO.File.Delete(fileName);
}
}
}
The System.IO.Compression namespace contains the following types for compressing and decompressing files and streams. You can also use these types to read and modify the contents of a compressed file.
string fileName = Guid.NewGuid() + ifile.FileName;
string path = Path.Combine(FilesTempPath, fileName);
using (var fileStream = new FileStream(path, FileMode.Create))
{
ifile.CopyTo(fileStream);
}
var FileZipPath = FilesTempPath + "\\" + fileName;
ZipFile.ExtractToDirectory(FileZipPath, FilesTempPath);
The following example from MSDN shows how to use the GZipStream class to compress and decompress a directory of files.
I am using Zip Archive to create a zip folder with various files and subfolders and returning it as a memory stream like so.
public MemoryStream CreateAZipFolder(){
var stMarged = new System.IO.MemoryStream();
stMarged.Position = 0;
using (MemoryStream zipStream = new MemoryStream())
{
using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
{
string[] fileEntries = Directory.GetFiles(#"C:\Applications\folder");
foreach (var fileName in fileEntries)
{
zip.CreateEntryFromFile(fileName, "Applications/folder/" + Path.GetFileName(fileName),
CompressionLevel.Optimal);
}
ZipArchiveEntry batchEntry = zip.CreateEntry("mybatchFile.bat");
using (StreamWriter writer = new StreamWriter(batchEntry.Open()))
{
writer.Write(batchFile);
}
//Add the xml file to zip folder
ZipArchiveEntry entry = zip.CreateEntry("nCounterConfig.xml");
using (StreamWriter writer = new StreamWriter(entry.Open()))
{
writer.Write(xdoc.OuterXml);
}
}
zipStream.Position = 0;
return zipStream;
I would like to add a directory with sub directories and files to this memory stream. I found that ZipFile has a method "CreateFromDirectory" which would be ideal except it requires a paramater for an output folder the method also does not have a return type. How can i zip all the files and subfolders in a directory and add them to my memory stream using ZipFile?
something like this
zip.CreateEntry(ZipFile.CreateFromDirectory(
#"C:\morefilestozip\", "",
CompressionLevel.Fastest, true));
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.
I want to compress a file and a directory in C#. I found some solution in Internet but they are so complex and I couldn't run them in my project. Can anybody suggest me a clear and effective solution?
You could use GZipStream in the System.IO.Compression namespace
.NET 2.0.
public static void CompressFile(string path)
{
FileStream sourceFile = File.OpenRead(path);
FileStream destinationFile = File.Create(path + ".gz");
byte[] buffer = new byte[sourceFile.Length];
sourceFile.Read(buffer, 0, buffer.Length);
using (GZipStream output = new GZipStream(destinationFile,
CompressionMode.Compress))
{
Console.WriteLine("Compressing {0} to {1}.", sourceFile.Name,
destinationFile.Name, false);
output.Write(buffer, 0, buffer.Length);
}
// Close the files.
sourceFile.Close();
destinationFile.Close();
}
.NET 4
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());
}
}
}
}
}
http://msdn.microsoft.com/en-us/library/ms404280.aspx
I'm adding this answer as I've found an easier way than any of the existing answers:
Install DotNetZip DLLs in your solution (easiest way is to install the package from nuget)
Add a reference to the DLL.
Import the namespace by adding: using Ionic.Zip;
Zip your file
Code:
using (ZipFile zip = new ZipFile())
{
zip.AddFile("C:\test\test.txt");
zip.AddFile("C:\test\test2.txt");
zip.Save("C:\output.zip");
}
If you don't want the original folder structure mirrored in the zip file, then look at the overrides for AddFile() and AddFolder() etc.
For .Net Framework 4.5 this is the most clear example I found:
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
You'll need to add a reference to System.IO.Compression.FileSystem
From: https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-compress-and-extract-files
There is a built-in class in System.IO.Packaging called the ZipPackage:
http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage(v=vs.100).aspx
http://www.icsharpcode.net/opensource/sharpziplib/
You can just use ms-dos command line program compact.exe.
Look on a parameters compact.exe in cmd and start this process using .NET method Process.Start().
Using DotNetZip http://dotnetzip.codeplex.com/, there's an AddDirectory() method on the ZipFile class that does what you want:
using (var zip = new Ionic.Zip.ZipFile())
{
zip.AddDirectory("DirectoryOnDisk", "rootInZipFile");
zip.Save("MyFile.zip");
}
Bonne continuation...
just use following code for compressing a file.
public void Compressfile()
{
string fileName = "Text.txt";
string sourcePath = #"C:\SMSDBBACKUP";
DirectoryInfo di = new DirectoryInfo(sourcePath);
foreach (FileInfo fi in di.GetFiles())
{
//for specific file
if (fi.ToString() == fileName)
{
Compress(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());
}
}
}
}
}
}
Use http://dotnetzip.codeplex.com/ to ZIP files or directory, there is no builtin class to do it directly in .NET
Source code taken from MSDN that is compatible to .Net 2.0 and above
public static void CompressFile(string path)
{
FileStream sourceFile = File.OpenRead(path);
FileStream destinationFile = File.Create(path + ".gz");
byte[] buffer = new byte[sourceFile.Length];
sourceFile.Read(buffer, 0, buffer.Length);
using (GZipStream output = new GZipStream(destinationFile,
CompressionMode.Compress))
{
Console.WriteLine("Compressing {0} to {1}.", sourceFile.Name,
destinationFile.Name, false);
output.Write(buffer, 0, buffer.Length);
}
// Close the files.
sourceFile.Close();
destinationFile.Close();
}
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);