0
我有这样的代码C#解压.GZIP到文件
using System.IO;
using System.IO.Compression;
...
UnGzip2File("input.gz","output.xls");
其中运行此程序,它运行没有错误,但之后,该input.gz是空的,创建output.xls也是空的。在开始input.gz有12MB。我究竟做错了什么 ?或者有更好的解决方案吗?
public static void UnGzip2File(string inputPath, string outputPath)
{
FileStream inputFileStream = new FileStream(inputPath, FileMode.Create);
FileStream outputFileStream = new FileStream(outputPath, FileMode.Create);
using (GZipStream gzipStream = new GZipStream(inputFileStream, CompressionMode.Decompress))
{
byte[] bytes = new byte[4096];
int n;
// To be sure the whole file is correctly read,
// you should call FileStream.Read method in a loop,
// even if in the most cases the whole file is read in a single call of FileStream.Read method.
while ((n = gzipStream.Read(bytes, 0, bytes.Length)) != 0)
{
outputFileStream.Write(bytes, 0, n);
}
}
outputFileStream.Dispose();
inputFileStream.Dispose();
}
当你打开一个文件阅读你不应该使用'Create'选项。 – 2014-09-20 20:30:59
确保为所有资源使用'using'。我不知道为什么人们在2014年仍然没有这样做,尽管这样做没有任何不利之处。 – usr 2014-09-20 20:44:39
usr:好的,谢谢你的提示。我发现使用block的优点是即使出错也能处理。 – Muflix 2014-09-20 20:47:33