鉴于下面的代码,为什么减压不起作用? “NewFile2.txt”应该有原始的解压缩文本,但文件只是空白。
ioTests.CompressFile(@"c:\newfile.txt", @"c:\newfile.txt.gz");
ioTests.DecompressFile(@"c:\newfile.txt.gz", @"c:\newfile2.txt");
public void CompressFile(string inFileName, string outFileName)
{
FileStream inFile = new FileStream(inFileName, FileMode.Open);
FileStream outFile = new FileStream(outFileName, FileMode.Create);
GZipStream compStream = new GZipStream(outFile, CompressionMode.Compress);
int theByte = inFile.ReadByte();
while (theByte != -1)
{
compStream.WriteByte((byte)theByte);
theByte = inFile.ReadByte();
}
compStream.Close();
}
public void DecompressFile(string inFileName, string outFileName)
{
FileStream inFile = new FileStream(inFileName, FileMode.Open);
FileStream outFile = new FileStream(outFileName, FileMode.CreateNew);
GZipStream compStream = new GZipStream(inFile, CompressionMode.Decompress);
int theByte = compStream.ReadByte();
while (theByte != -1)
{
outFile.WriteByte((byte)theByte);
theByte = compStream.ReadByte();
}
compStream.Close();
}
答案 0 :(得分:4)
outFile.Flush(); // after your loop
答案 1 :(得分:2)
我更喜欢
outFile.Close()
因为它刷新流并调用Dispose方法,释放分配的资源。
答案 2 :(得分:2)
由于您使用的流实现IDisposable
interface,您应该Dispose()
/ Close()
您的类,或使用using
语句自动执行此操作:
using (FileStream inFile = new FileStream(inFileName, FileMode.Open))
using (FileStream outFile = new FileStream(outFileName, FileMode.Create))
using (GZipStream compStream = new GZipStream(outFile, CompressionMode.Compress)) {
int theByte = inFile.ReadByte();
// ... Rest of your code
}
这大致转换为:
try {
FileStream inFile = new FileStream(inFileName, FileMode.Open);
FileStream outFile = new FileStream(outFileName, FileMode.Create);
GZipStream compStream = new GZipStream(outFile, CompressionMode.Compress);
int theByte = inFile.ReadByte();
// ... Rest of your code
} finally {
if (inFile != null) inFile.Dispose();
if (outFile != null) outFile.Dispose();
if (compStream != null) compStream.Dispose();
}