开发者

GZipStream not working

I am using the following C# code to compress a file:

// Open the stream we want to compress
FileStream fs = File.Create(@"C:\Projects\Samples\test\compressed.zip", 0);

// Creates the GZipStream
GZipStream gzip = new GZipStream(fs, CompressionMode.Compress);

// Reading the content to compress
 byte[] bytes = File.ReadAllBytes(@"C:\Projects\Samples\samplefile.xml");

// Writing compressed content
gzip.Write(bytes, 0, bytes.Length);
gzip.Close();  // This also closes the FileStream (the underlying stream)

However, when I extract the file from windows explorer the file loses it's extension so instead of samplefile.xml it just becomes samplefile. Same thing happened with .txt file not just .xml file.

Can you开发者_StackOverflow help me see what I'm doing wrong?


ok found the problem:

Line 2 has to be as follows:

FileStream fs = File.Create(@"C:\Projects\Samples\test\compressed.xml.zip", 0);


GZipStream doesn't create zip archives. It creates a gzip file, which contains only one file, and doesn't necessarily store a filename at all. Normally you should use the .gz extension to identify a gzip file, and it's conventional to use the entire name of the original file with .gz appended on the end. See also here for more information about gzip format: http://en.wikipedia.org/wiki/Gzip#File_format

If you actually want to create zip archives, you might want to use a library like SharpZipLib: http://www.icsharpcode.net/opensource/sharpziplib/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜