C#GZipStream压缩不写入文件

时间:2015-09-25 14:32:35

标签: c# gzipstream

我有这个简单的例子(从MSDN文档中复制),但是从未创建.gz文件......

我试图添加对compressedFileStream.Flush()的调用;但没什么......

static string directoryPath = @"C:\\temp\\";
...
public string CompressFile(FileInfo fileToCompress)
{
    try
    {
        using (FileStream originalFileStream = fileToCompress.OpenRead())
        {
            if ((File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
            {
                using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
                using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
                {
                    originalFileStream.CopyTo(compressionStream);
                    compressedFileStream.Flush();

                    FileInfo info = new FileInfo(directoryPath + "\\" + fileToCompress.Name + ".gz");

                    return String.Format("Compressed {0} from {1} to {2} bytes.", fileToCompress.Name, fileToCompress.Length.ToString(), info.Length.ToString());
                }
            }
            return "File yet compressed.";
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    }

    return "";
}

1 个答案:

答案 0 :(得分:1)

您的代码运行正常。我只是运行它,我传递了文件的名称,我得到了gzipped文件。请记住,您的gz文件将在与原始文件相同的目录中创建。我看到你有directoryPath变量,并且你正在使用它来读取有关新创建文件的信息。确保directoryPath和您传递的文件位于同一目录中。一种方法是在调用函数时使用directoryPath变量。例如

var result = CompressFile(new FileInfo(directoryPath +  "FileToCompress.txt"));

我得到了结果:

  

压缩FileToCompress.txt,从10920到10个字节。