【发布时间】:2011-11-12 16:41:19
【问题描述】:
我是 .net 的新手。我在 C# 中做压缩和解压缩字符串。有一个 XML,我正在转换为字符串,然后我进行压缩和解压缩。我的代码中没有编译错误,除非我解压缩代码并返回我的字符串,它只返回一半的 XML。
以下是我的代码,请纠正我的错误。
代码:
class Program
{
public static string Zip(string value)
{
//Transform string into byte[]
byte[] byteArray = new byte[value.Length];
int indexBA = 0;
foreach (char item in value.ToCharArray())
{
byteArray[indexBA++] = (byte)item;
}
//Prepare for compress
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress);
//Compress
sw.Write(byteArray, 0, byteArray.Length);
//Close, DO NOT FLUSH cause bytes will go missing...
sw.Close();
//Transform byte[] zip data to string
byteArray = ms.ToArray();
System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length);
foreach (byte item in byteArray)
{
sB.Append((char)item);
}
ms.Close();
sw.Dispose();
ms.Dispose();
return sB.ToString();
}
public static string UnZip(string value)
{
//Transform string into byte[]
byte[] byteArray = new byte[value.Length];
int indexBA = 0;
foreach (char item in value.ToCharArray())
{
byteArray[indexBA++] = (byte)item;
}
//Prepare for decompress
System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray);
System.IO.Compression.GZipStream sr = new System.IO.Compression.GZipStream(ms,
System.IO.Compression.CompressionMode.Decompress);
//Reset variable to collect uncompressed result
byteArray = new byte[byteArray.Length];
//Decompress
int rByte = sr.Read(byteArray, 0, byteArray.Length);
//Transform byte[] unzip data to string
System.Text.StringBuilder sB = new System.Text.StringBuilder(rByte);
//Read the number of bytes GZipStream red and do not a for each bytes in
//resultByteArray;
for (int i = 0; i < rByte; i++)
{
sB.Append((char)byteArray[i]);
}
sr.Close();
ms.Close();
sr.Dispose();
ms.Dispose();
return sB.ToString();
}
static void Main(string[] args)
{
XDocument doc = XDocument.Load(@"D:\RSP.xml");
string val = doc.ToString(SaveOptions.DisableFormatting);
val = Zip(val);
val = UnZip(val);
}
}
我的 XML 大小是 63KB。
【问题讨论】:
-
我怀疑如果使用 UTF8Encoding(或 UTF16 或诸如此类)和 GetBytes/GetString,问题会“自行解决”。它还将大大简化代码。也推荐使用
using。 -
你不能像你一样将 char 转换为 byte 和反向(使用简单的转换)。您需要使用一种编码,并使用相同的编码进行压缩/解压缩。请参阅下面的 xanatos 答案。
-
@pst 不会的;你会以错误的方式使用
Encoding。根据 xanatos 的回答,您在这里需要 base-64 -
@Marc Gravell True,错过了签名/意图的那部分。绝对不是我的首选签名。
标签: c# string .net-2.0 compression