简体   繁体   中英

C# GZipStream compression not writing to file

I have this simple example (copied from the MSDN documentation), but the .gz file get never created...

I have tried to add a call to 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 . I see that you have directoryPath variable, and you are using it to read information about new create file. Make sure that directoryPath and the file that you pass are in the same directory. One way of doing it is to use your directoryPath variable when you call your function. For instance

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

I got result back as:

Compressed FileToCompress.txt from 10920 to 10 bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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