我想压缩包含二进制数据的文件,并将压缩数据保存在另一个文件中:
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();
我收到以下错误:
无法从'byte []'转换为'char []'
排队:
writer.Write(File.ReadAllBytes("file_to_be_compressed.bin"), 0, File.ReadAllBytes("file_to_be_compressed.bin").Length)
将文件的二进制数据转换为字节数组是否合适,或者将文件的二进制数据作为流传递更好?
注意:CopyTo在.NET 2.0中不可用
答案 0 :(得分:0)
根据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);
}
}
}