我是.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 …Run Code Online (Sandbox Code Playgroud) 我遇到了这个测试函数的问题,我在其中获取内存字符串,压缩它并解压缩它.压缩效果很好,但我似乎无法使解压缩工作.
//Compress
System.IO.MemoryStream outStream = new System.IO.MemoryStream();
GZipStream tinyStream = new GZipStream(outStream, CompressionMode.Compress);
mStream.Position = 0;
mStream.CopyTo(tinyStream);
//Decompress
outStream.Position = 0;
GZipStream bigStream = new GZipStream(outStream, CompressionMode.Decompress);
System.IO.MemoryStream bigStreamOut = new System.IO.MemoryStream();
bigStream.CopyTo(bigStreamOut);
//Results:
//bigStreamOut.Length == 0
//outStream.Position == the end of the stream.
Run Code Online (Sandbox Code Playgroud)
我相信bigStream out应该至少包含数据,特别是如果我的源流(outStream)被读取.这是一个MSFT错误还是我的?