【发布时间】:2012-01-31 18:03:14
【问题描述】:
我的目标是使用 gzip 压缩文件,然后将压缩字节写入 Xml 部分,这意味着我的代码中需要压缩字节数组。我发现的所有 GZip 示例都只是将字节直接写入文件。
这是我的代码:
public ContainerFile(string[] inputFiles, string Output)
{
XmlDocument doc = new XmlDocument();
XmlNode root;
FileInfo fi;
FileStream fstream;
BinaryReader reader;
GZipStream gstream;
root = doc.CreateElement("compressedFile");
doc.AppendChild(root);
foreach (string f in inputFiles)
{
fstream = File.OpenRead(f);
MemoryStream s = new MemoryStream();
byte[] buffer = new byte[fstream.Length];
// Read the file to ensure it is readable.
int count = fstream.Read(buffer, 0, buffer.Length);
if (count != buffer.Length)
{
fstream.Close();
//Console.WriteLine("Test Failed: Unable to read data fromfile");
return;
}
fstream.Close();
gstream = new GZipStream(s, CompressionMode.Compress, true);
gstream.Write(buffer, 0, buffer.Length);
gstream.Flush();
byte[] bytes = new byte[s.Length];
s.Read(bytes, 0, bytes.Length);
File.WriteAllBytes(@"c:\compressed.gz", bytes);
}
出于调试原因,我只是在加载后尝试将数据写入文件。
因此,输入文件的长度约为 4k 字节。正如 deguber 向我展示的那样,“字节”数组的长度约为 2k。所以看起来压缩后的字节数组的大小是对的,但是里面所有的值都是0。
可以。帮帮我?
【问题讨论】: