公司的老舊系統是採用 ASCII Code,
因此中文字是 2bytes,而英文字母則是 1bytes!
假設這是舊系統資料庫中的某張 table 表:(說明1 6bytes, 說明2 4bytes, 說明3 6bytes)
產品 說明1 說明2 說明3
A 藍色12 塑膠 12kg
B 紅3 金屬 2kg
C green PVC 0.9kg
經過轉換至 BI 系統的 SQL Server 時,把說明1.2.3欄位合併在一起如下:(不足長度的會塞入空白字元,這裡我用_表示)
product_id product_spec
A 藍色12塑膠12kg__
B 紅3___金屬2kg___
C green_PVC_0.9kg_
我要從 BI 系統中的新 table 表取得舊系統中的說明3資料時,問題出現了!
因為 .NET 中預設是以 Unicode UTF-16 來表示字元,不管中.英文,都是以1個字元來表示,
直接以 substring 將資料庫取回的字串切位,無法取得正確的資料,
此時就必須先將從資料庫取得的字串轉成 ASCII 的 Bytes 陣列,
計算好要取得的陣列範圍(例如要取得說明3,就是抓取 Bytes 陣列中的第11~16 個元素),
再把新的 Bytes 陣列轉換為 String。
private void button2_Click(object sender, EventArgs e) { System.Text.Encoding myEncoding = System.Text.Encoding.GetEncoding(950); Byte[] myBytes; string mystring; mystring = textBox1.Text; myBytes = myEncoding.GetBytes(mystring); Byte[] myOutputBytes = new Byte [4]; int i; int j; string[] myOutputstring= new string [3]; for (i=0;i<=2;i++) { for (j=0;j<=3;j++) { myOutputBytes[j]= myBytes[i*4+j]; } myOutputstring[i]= myEncoding.GetString(myOutputBytes); } label1.Text = myOutputstring[0]; label2.Text = myOutputstring[1]; label3.Text = myOutputstring[2]; }