1. Convert string to binary array
String content = "this is a test! ";
System. Text. UnicodeEncoding converter = new System. Text. UnicodeEncoding ();
Byte [] byteArr = converter. GetBytes (content );
2. Convert the binary array into a string
Copy codeThe Code is as follows:
System. Text. UnicodeEncoding converter = new System. Text. UnicodeEncoding ();
String spcontent = converter. GetString (byteArr );
During compilation, files are saved to the database using binary data. For example, you can save the "C: \ test.html" file to the database and read it out:
1. Save the file as a stream to the database:
Copy codeThe Code is 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)
{// You can perform corresponding processing here, such as filtering data in the file.
Sb. Append (sLine );
}
}
ObjReader. Close ();
Content = sb. ToString (); // if you want to display the content of the entire file on the interface, you can use <% = content %> to place it in the corresponding place.
System. Text. UnicodeEncoding converter = new System. Text. UnicodeEncoding ();
Byte [] byteArr = converter. GetBytes (content );
// The following code is inserted into the database,
StrInsertCmd = "insert into Document (partition entid, DocumentContent, addtime, MODITIME, status) values ('" + partition entid + "',?, '"+ 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 and saving as a file or string from the database is the opposite of step 1.
1. Convert GB2312 data to UTF-8 data as follows (other codes and so on ):
Copy codeThe Code is 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;
}