I'm using DotNetZIP(Ionic utility) to ZIP my files.But my client says "no" to it.They wanted me to use WinZip to ZIP the file.
I'm using MS provied GZIP(its OK for client) like this:
using(GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
How can I save the compression stream?it seems that there is no method available for VS2008/.Net3.5.
Searched on net but not got any suitable link or solution.Could any one please help on this?
You can follow this link
http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream(v=vs.90).aspx
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.
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
{
Compress.Write(buffer, 0, numRead);
}
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fi.Name, fi.Length.ToString(), outFile.Length.ToString());
}
}
}
}
}
Related
I want to compress a Excel file to .zip or .cap extension. The code Used to do that it is compressing the file but that zip file can't be unzip. while unzip that i am getting the error file file corrupted or can't be unzip.
The code I am using:
static public bool CompressFile(string file, string outputFile)
{
try
{
using (var inFile = File.OpenRead(file))
{
using (var outFile = File.Create(outputFile))
{
using (var compress = new GZipStream(outFile, CompressionMode.Compress, false))
{
byte[] buffer = new byte[inFile.Length];
int read = inFile.Read(buffer, 0, buffer.Length);
while (read > 0)
{
compress.Write(buffer, 0, read);
read = inFile.Read(buffer, 0, buffer.Length);
}
}
}
}
return true;
}
catch (IOException ex)
{
MessageBox.Show(string.Format("Error compressing file: {0}", ex.Message));
return false;
}
}
Even i go some link to get the proper solution. But nothing is workout.I need some suggestion to get the proper solution. Any answer please.
This code uses the SharpZipLib library and will compress files that can be uncompressed no problems
private void Zip()
{
string output = #"C:\TEMP\test.zip";
string input = #"C:\TEMP\test.xlsx";
using (var zipStream = new ZipOutputStream(System.IO.File.Create(output)))
{
zipStream.SetLevel(9);
var buffer = new byte[4096];
var entry = new ZipEntry(Path.GetFileName(input));
zipStream.PutNextEntry(entry);
using (FileStream fs = System.IO.File.OpenRead(input))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
zipStream.Finish();
zipStream.Close();
}
}
When I use the same GZipStream to compress file blocks in loop the result file compress successfully:
public static void Compress1(string fi)
{
using (FileStream inFile = File.Open(fi,FileMode.Open,FileAccess.Read,FileShare.Read))
{
using (FileStream outFile = File.Create(fi + ".gz"))
{
using (GZipStream Compress = new GZipStream(outFile,
CompressionMode.Compress))
{
byte[] buffer = new byte[6315120];
int numRead;
while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
{
Compress.Write(buffer, 0, numRead);
}
}
}
}
}
But when I compress file blocks separately in different streams the result file corrupts:
public static void Compress2(string fi, int offset)
{
using (FileStream inFile = File.Open(fi,FileMode.Open))
{
using (FileStream outFile = File.OpenOrCreate(fi + ".gz"))
{
using (GZipStream Compress = new GZipStream(outFile,
CompressionMode.Compress))
{
// Copy the source file into the compression stream.
byte[] buffer = new byte[6315120];
int numRead=-1;
inFile.Seek(offset,SeekOrigin.Begin);
numRead = inFile.Read(buffer, 0, buffer.Length);
Compress.Write(buffer, 0, numRead);
}
}
}
}
In these examples I have a file with size = 12630240. And devide it into 2 blocks, size of each block = 6315120 (buffer size). So, the first block compress correctly in both methods, but the second block in second method compress different from the first method. What I missed?
What is happening is you are creating to different files as each GZipStream has its one headers
by dividing what you are doing is creating to different GZ files and if you write the two to the same file it is a corrupt file.
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();
}
I need to compress a file using GZip by batch of specified size (not in a whole). I can successfuly fill the byte[] buffer, but after copying it into the compression stream, it just leaves the output stream empty.
public void Compress(string source, string output)
{
FileInfo fi = new FileInfo(source);
byte[] buffer = new byte[BufferSize];
int total, current = 0;
using (FileStream inFile = fi.OpenRead())
{
using (FileStream outFile = File.Create(output + ".gz"))
{
while ((total = inFile.Read(buffer, 0, buffer.Length)) != 0)
{
using (MemoryStream compressedStream = new MemoryStream())
{
using (MemoryStream bufferStream = new MemoryStream())
{
CopyToStream(buffer, bufferStream);
using (GZipStream Compress = new GZipStream(compressedStream, CompressionMode.Compress, true))
{
bufferStream.Position = 0;
bufferStream.CopyTo(Compress);
current += total;
}
compressedStream.Position = 0;
compressedStream.CopyTo(outFile);
}
}
}
}
}
}
static void CopyToStream(byte[] buffer, Stream output)
{
output.Write(buffer, 0, buffer.Length);
}
You need to rewind compressedStream by setting Position=0 before compressedStream.CopyTo(outFile);.
You are trying to over complicate things... You do not require additional MemoryStreams or buffers...
Taken from the MSDN... http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx
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());
}
}
}
}
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
how to read a *.file
how to compress and uncompress a text file
Hi,
I am having a problem in uncompressing the zip file into a text file,
when i compress the text file into a zip file (Ex-20110530.txt to 20110530.zip) .my code is compressing the code i use for compressing the text file to a zip file is
string path = (string)(Application.StartupPath + "\\TEMP\\TEMP_BACKFILL_atoz" + "\\" + name_atoz);
StreamWriter Strwriter = new StreamWriter(path);
DirectoryInfo di = new DirectoryInfo(path);
FileInfo fi = new FileInfo(path);
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.Name != ".zip")
{
// Create the compressed file.
using (FileStream outFile = File.Create(System.Text.RegularExpressions.Regex.Replace(fi.FullName, ".txt$", "") + ".zip"))
{
using (GZipStream Compress = new GZipStream(outFile,
CompressionMode.Compress))
{
// Copy the source file into the compression stream.
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
{
Compress.Write(buffer, 0, numRead);
}
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fi.Name, fi.Length.ToString(), outFile.Length.ToString());
}
}
}
}
}
this code creates a zip file when i unzip the file it creates a file called 20110530 not a 20110530.txt .
I want the file to be uncompress with 20110530.txt format
the code i use to uncompress the file is
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.
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = Decompress.Read(buffer, 0, buffer.Length)) != 0)
{
outFile.Write(buffer, 0, numRead);
}
Console.WriteLine("Decompressed: {0}", fi.Name);
}
}
}
}
Can Anyone Pls Help Me,
Thanks In Advance.
Seems to me that this line:
string origName = curFile.Remove(curFile.Length - fi.Extension.Length);
Removes the extension from the string, but you use that line when creating the uncompressed stream.
using (FileStream outFile = File.Create(origName))
Instead, use this:
using (FileStream outFile = File.Create(origName + ".txt"))
and that should create the uncompressed file with a TXT extension.
That is because you remove the extension when you compress the file so that it becomes 20110530.zip instead of 20110530.txt.zip. The code that decompresses the file uses everything before .zip as file name, so naturally you end up with 20110530 instead of 20110530.txt.
Make sure to include the original file extension when you create a file in Decompress
//Create the decompressed file.
using (FileStream outFile = File.Create(origName)) // <<<-- here