GZipStream 不工作
我正在使用以下 C# 代码来压缩文件:
// 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)
但是,当我从 Windows 资源管理器中提取文件时,该文件会丢失其扩展名,因此它不再是 Samplefile.xml,而是变成了 Samplefile。 .txt 文件也发生了同样的情况,而不仅仅是 .xml 文件。
你能帮我看看我做错了什么吗?
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 help me see what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,发现问题了:
第 2 行必须如下所示:
FileStream fs = File.Create(@"C:\Projects\Samples\test\compressed.xml.zip", 0);
ok found the problem:
Line 2 has to be as follows:
FileStream fs = File.Create(@"C:\Projects\Samples\test\compressed.xml.zip", 0);
GZipStream 不创建 zip 存档。它创建一个 gzip 文件,该文件仅包含一个文件,并且根本不需要存储文件名。通常,您应该使用
.gz
扩展名来标识 gzip 文件,并且通常使用原始文件的整个名称并在末尾附加.gz
。另请参阅此处有关 gzip 格式的更多信息: http://en.wikipedia.org/wiki/Gzip #File_format如果您确实想创建 zip 存档,您可能需要使用像 SharpZipLib 这样的库: http://www.icsharpcode.net/opensource/sharpziplib/
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_formatIf you actually want to create zip archives, you might want to use a library like SharpZipLib: http://www.icsharpcode.net/opensource/sharpziplib/