我是.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) 我正在尝试连接到一个api,它从WCF服务(WCF服务到WCF服务)返回GZip编码的JSON.我正在使用HTTPClient连接到API,并且能够将JSON对象作为字符串返回.但是我需要能够将这些返回的数据存储在数据库中,因此我认为最好的方法是将JSON对象返回并存储在数组或字节中或沿着这些行存储.
我特别遇到的问题是GZip编码的解压缩,并且尝试了很多不同的例子,但仍然无法得到它.
下面的代码是我建立连接和获得响应的方式,这是从API返回字符串的代码.
Run Code Online (Sandbox Code Playgroud)public string getData(string foo) { string url = ""; HttpClient client = new HttpClient(); HttpResponseMessage response; string responseJsonContent; try { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); response = client.GetAsync(url + foo).Result; responseJsonContent = response.Content.ReadAsStringAsync().Result; return responseJsonContent; } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); return ""; } }
我一直在关注一些不同的例子,比如这些StackExchange API,MSDN和一些关于stackoverflow,但我无法让任何这些对我有用.
实现这一目标的最佳方法是什么,我是否在正确的轨道上?
多谢你们.