未压缩的文件比GZIP中的原始文件大
本文关键字:文件 原始 未压缩 GZIP | 更新日期: 2023-09-27 18:10:36
我使用下面的函数来压缩(感谢http://www.dotnetperls.com/):
)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);
}
}
解压:
static byte[] Decompress(byte[] gzip)
{
// Create a GZIP stream with decompression mode.
// ... Then create a buffer and write into while reading from the GZIP stream.
using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
{
const int size = 4096;
byte[] buffer = new byte[size];
using (MemoryStream memory = new MemoryStream())
{
int count = 0;
do
{
count = stream.Read(buffer, 0, size);
if (count > 0)
{
memory.Write(buffer, 0, count);
}
}
while (count > 0);
return memory.ToArray();
}
}
}
所以我的目标实际上是压缩日志文件,然后在内存中解压缩它们,并将未压缩的文件与原始文件进行比较,以检查压缩是否成功,我是否能够成功打开压缩文件。问题是未压缩的文件大多数时候比原始文件大,我的比较检查失败,尽管压缩可能成功。
知道为什么吗?
btw这是我如何比较未压缩文件和原始文件:
static bool FileEquals(byte[] file1, byte[] file2)
{
if (file1.Length == file2.Length)
{
for (int i = 0; i < file1.Length; i++)
{
if (file1[i] != file2[i])
{
return false;
}
}
return true;
}
return false;
}
尝试以下方法压缩文件:
public static byte[] Compress(byte[] raw)
{
using (MemoryStream memory = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(memory,
CompressionMode.Compress, true))
{
gzip.Write(raw, 0, raw.Length);
}
return memory.ToArray();
}
}
}
解压:
static byte[] Decompress(byte[] gzip)
{
// Create a GZIP stream with decompression mode.
// ... Then create a buffer and write into while reading from the GZIP stream.
using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
{
const int size = 4096;
byte[] buffer = new byte[size];
using (MemoryStream memory = new MemoryStream())
{
int count = 0;
do
{
count = stream.Read(buffer, 0, size);
if (count > 0)
{
memory.Write(buffer, 0, count);
}
}
while (count > 0);
return memory.ToArray();
}
}
}
}
告诉我它是否有效。
古德勒克。
认为使用最简单的API调用会更好,请尝试Stream.CopyTo()。我在你的代码中找不到错误。如果是我在做的话,我可能会确保所有的东西都被冲洗干净…不记得GZipStream是否会在using块关闭时将其输出刷新到FileStream ..但是你也说最终文件更大,而不是更小。
总之,这是我经验中最好的策略……当你不需要的时候,不要重写容易出错的代码。至少你测试过了;)