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;
}