时间:2021-07-01 10:21:17 帮助过:6人阅读
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;
}