c#压缩html代码_c#压缩与解压byte数组

发布时间:2020-05-08编辑:脚本学堂
c#压缩文件的二例代码,c#实现压缩html代码与c#压缩与解压byte数组,通过这二个例子,可以掌握C#压缩文件、c#压缩网页源码、c#压缩与解压缩数组的方法。

对网页文件进行压缩,可以减少网络传输量,提高网页的访问速度,在实际应用中,经常需要对网页文件、对图片等进行适当比例的压缩处理。

一、c#压缩html文件代码
 

复制代码 代码示例:
/// <summary>
/// 压缩html代码
/// </summary>
/// <param name="writer"></param>
protected override void Render(HtmlTextWriter writer)
{
System.IO.StringWriter html = new System.IO.StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(html);
base.Render(tw);
string outhtml = html.ToString();
outhtml = System.Text.RegularExpressions.Regex.Replace(outhtml, "n+s+", string.Empty);
outhtml = outhtml.Trim();
writer.Write(outhtml);
}

另外,需要禁用不必要的viewstate:
页面中看不懂的一堆长字符串就是viewstate,这大概会占用15%~40%左右的html代码量,减少viewstate势在必行,如果当前页面没有使用任何viewstate,快速关闭控件的代码:
 

复制代码 代码示例:
protected override void Render(HtmlTextWriter writer)
{
  System.IO.StringWriter html = new System.IO.StringWriter();
  HtmlTextWriter tw = new HtmlTextWriter(html);
  base.Render(tw);
  string outhtml = html.ToString();
  outhtml = System.Text.RegularExpressions.Regex.Replace(outhtml, "<inputstype="hidden"sname="__VIEWSTATE"sid="__VIEWSTATE" value=".+/>", string.Empty);
  outhtml = outhtml.Trim();
  writer.Write(outhtml);
}

二、c#压缩与解压byte数组

一个简单的文件压缩和解压的例子
代码:
 

复制代码 代码示例:
/// <summary>
/// 压缩数据
/// </summary>
public class gzip
{
/// <summary>
/// 将字节数组进行压缩后返回压缩的字节数组
/// </summary>
/// <param name="data">需要压缩的数组</param>
/// <returns>压缩后的数组</returns>
public static byte[] Compress(byte[] data)
{
MemoryStream stream = new MemoryStream();
GZipStream gZipStream = new GZipStream(stream, CompressionMode.Compress);
gZipStream.Write(data, 0, data.Length);
gZipStream.Close();
return stream.ToArray();
}
 
/// <summary>
/// 解压字符数组
/// </summary>
/// <param name="data">压缩的数组</param>
/// <returns>解压后的数组</returns>
public static byte[] Decompress(byte[] data)
{
MemoryStream stream = new MemoryStream();
 
GZipStream gZipStream = new GZipStream(new MemoryStream(data), CompressionMode.Decompress);
 
byte[] bytes = new byte[40960];
int n;
while ((n = gZipStream.Read(bytes, 0, bytes.Length)) != 0)
{
stream.Write(bytes, 0, n);
}
gZipStream.Close();
return stream.ToArray();
}
}