0

I want to compress a file that has binary data and save the compressed data in another file:

FileStream fileStream = new FileStream("compressed_file.bin", FileMode.Create, FileAccess.Write);
GZipStream compressionStream = new GZipStream(fileStream, CompressionMode.Compress);
StreamWriter writer = new StreamWriter(compressionStream);
writer.Write(File.ReadAllBytes("file_to_be_compressed.bin"), 0, File.ReadAllBytes("file_to_be_compressed.bin").Length);
writer.Close();

I get following error:

cannot convert from 'byte[]' to 'char[]'

in line:

writer.Write(File.ReadAllBytes("file_to_be_compressed.bin"), 0, File.ReadAllBytes("file_to_be_compressed.bin").Length)

And is it fine to convert the binary data of file to byte array, or is it better to pass binary data of file as stream?

Note: CopyTo is not available in .NET 2.0

Computer User
  • 2,839
  • 4
  • 47
  • 69

1 Answers1

0

Try this, according to http://www.dotnetperls.com/gzipstream

using System.IO;
using System.IO.Compression;
using System.Text;

class Program
{
    static void Main()
    {
    try
    {
        // 1.
        // Starting file is 26,747 bytes.
        string anyString = File.ReadAllText("TextFile1.txt");

        // 2.
        // Output file is 7,388 bytes.
        CompressStringToFile("new.gz", anyString);
    }
    catch
    {
        // Could not compress.
    }
    }

    public static void CompressStringToFile(string fileName, string value)
    {
    // A.
    // Write string to temporary file.
    string temp = Path.GetTempFileName();
    File.WriteAllText(temp, value);

    // B.
    // Read file into byte array buffer.
    byte[] b;
    using (FileStream f = new FileStream(temp, FileMode.Open))
    {
        b = new byte[f.Length];
        f.Read(b, 0, (int)f.Length);
    }

    // C.
    // Use GZipStream to write compressed bytes to target file.
    using (FileStream f2 = new FileStream(fileName, FileMode.Create))
    using (GZipStream gz = new GZipStream(f2, CompressionMode.Compress, false))
    {
        gz.Write(b, 0, b.Length);
    }
    }
}
Yuriy Zaletskyy
  • 4,983
  • 5
  • 34
  • 54