1
votes

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 "";
}
1
Why do you have a single & in FileAttributes.Hidden & fileToCompress.Extension != ".gz" instead of &&?Solomon Rutzky
@spiderman77 do you still have an issue with it?Vlad Bezden

1 Answers

1
votes

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.