1. String binary array
String Content= "This is a test!" ";
System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding ();
byte[] Bytearr = converter. GetBytes (content);
2. Binary array to string
Copy Code code as follows:
System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding ();
String spcontent = converter. GetString (Bytearr);
In programming, you will encounter situations where you save a file in binary data to a database to save the "C:\test.html" file to a database and read it as an example:
1. Save the file as a stream to the database:
Copy Code code as follows:
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)
{//here can do the corresponding processing, such as filtering the data in the file
Sb. Append (sline);
}
}
Objreader.close ();
Content= sb. ToString (); If you want to display the entire contents of the file in the interface, you can use <%=content%> to place the corresponding
System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding ();
byte[] Bytearr = converter. GetBytes (content);
The following is inserted into the database code,
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) {//success! }
2. Reading from a database save as a file or string and step 1 is a reverse process
1. Convert GB2312 data to UTF-8 data as follows (other coding analogies):
Copy Code code as follows:
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;
}