当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > asp.net 字符串、二进制、编码数组转换函数

ASP.NET
Check if a File is in Internet Explorers Cache
如何检测电脑是否安装了.net framework
[Regex]Greta不支持“Named Groups”特性
使用子類化的方法來實現VB對特殊消息的響應
C#软件启动设计
C#中虛函數,抽象,接口的簡單説明
TreeView的操作
InteliIM 3.0 will be released soon!
如何將 Visual Basic 與 ADO 搭配使用
建立永遠停留在最上層的窗口(VB)
C#中比较两个值型一维数组变量是否值相等
谈谈软件工程设计的艺术
批量添加Active Directory帐号
文件搜索的实现(深度搜索)
一个图形分割问题[答网友]
XML反串行化Namespace不统一而引起的错误
使用Javascript创建XML文件
突破MsComm控件RThreshold限制,全部数据统统收!
如何制作一个带启动屏幕的窗体
【翻译】Managed DirectX(第五章)

ASP.NET 中的 asp.net 字符串、二进制、编码数组转换函数


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-20   浏览: 415 ::
收藏到网摘: n/a

字符串和二进制数组转换、将HTML文件显示为页面的一部分、UTF8和GB2312之间的转换 1.字符串转二进制数组
string content="这是做个测试!";
System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
byte[] byteArr = converter.GetBytes(content);
2.二进制数组转为字符串
复制代码 代码如下:

System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
string spcontent = converter.GetString(byteArr );

在编程中会遇到将文件以二进制数据保存到数据库的情况,以将"C:\test.html"文件保存到数据库和读取出来为例:
1.将文件以流的形式保存到数据库中:
复制代码 代码如下:

int itag=0;
      string content = "";
      StringBuilder sb = new StringBuilder();
       string fileName = @"c:\test.html";
StreamReader objReader = new StreamReader(fileName, System.Text.Encoding.GetEncoding("gb2312"));
string sLine = "";
while (sLine != null)
   {
   sLine = objReader.ReadLine();
  if (sLine != null)
  {//这里可以做相应的处理,如过滤文件中的数据
   sb.Append(sLine);
   }
 }
objReader.Close();
content= sb.ToString(); //如果你要将整个文件的内容显示在界面上,你可以用<%=content%>放到相应的地方
      System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
      byte[] byteArr = converter.GetBytes(content);
//下面为插入到数据库代码,
strInsertCmd = "insert into Document (DocumentID,DocumentContent,addtime,MODITIME,status) values ('" + DocumentID + "',?,'" + NOWTIME + "','" + NOWTIME + "',' 00 ')";
cmd=new OleDbCommand(strInsertCm,ConnectionOBJ);
param = new OleDbParameter("DocumentContent", OleDbType.VarBinary, byteArr.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, byteArr);
cmd.Parameters.Add(param);
itag=cmd.ExecuteNonQuery();
if(itag>0){//成功!}

2.从数据库中读取保存为文件或者字符串和步骤1是一个相反的过程

1.将GB2312数据转换为UTF-8数据如下(其他的编码类推):
复制代码 代码如下:

public string GB2312ToUTF8(string sSourse) {
string Utf8_info = string.Empty;
Encoding utf8 = Encoding.UTF8;
Encoding gb2312 = Encoding.GetEncoding("gb2312");
byte[] unicodeBytes = gb2312.GetBytes(sSourse);
byte[] asciiBytes = Encoding.Convert(gb2312, utf8, unicodeBytes);
char[] asciiChars = new char[utf8.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
utf8.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
Utf8_info = new string(asciiChars);
return Utf8_info;
}