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