简体   繁体   English

C#GZipStream压缩未写入文件

[英]C# GZipStream compression not writing to file

I have this simple example (copied from the MSDN documentation), but the .gz file get never created... 我有这个简单的示例(从MSDN文档复制),但从未创建.gz文件...

I have tried to add a call to compressedFileStream.Flush(); 我试图添加对compressedFileStream.Flush()的调用; but nothing... 但是什么都没有

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 "";
}

Your code works fine. 您的代码工作正常。 I just ran it and I passed name of the file and I got gzipped file back. 我刚运行它,并通过了文件名,然后将文件压缩回去。 Keep in mind that your gz file will be created in the same directory as an original file . 请记住,您的gz文件将在与原始文件相同的目录中创建。 I see that you have directoryPath variable, and you are using it to read information about new create file. 我看到您有directoryPath变量,并且您正在使用它来读取有关新创建文件的信息。 Make sure that directoryPath and the file that you pass are in the same directory. 确保directoryPath和您传递的文件在同一目录中。 One way of doing it is to use your directoryPath variable when you call your function. 一种实现方法是在调用函数时使用directoryPath变量。 For instance 例如

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

I got result back as: 我得到的结果是:

Compressed FileToCompress.txt from 10920 to 10 bytes. 将FileToCompress.txt从10920压缩到10个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM