ASP.NET中的編碼

來源:互聯網
上載者:User

using System;
using System.Text;
using System.IO;
namespace CharAndString
{
 class Class1
 {
  static void Main(string[] args)
  {
   //字串類 String 中的內容是 UNICODE 字串:
   string str = "中文123";
   // 得到長度為 5,因為是 5 個字元
   Console.WriteLine(str.Length);
   //字串和位元組串相互轉化
   // 按照 GB2312 得到位元組(得到多位元組字串)
   Encoding gb=Encoding.GetEncoding("gb2312");
   byte[] bytes = gb.GetBytes(str);
   char[] chars = gb.GetChars(bytes);//從位元組按照 GB2312 得到字元數組  
   str = gb.GetString(bytes);// 從位元組按照 GB2312 得到 UNICODE 字串
   // 要將 String 按照某種編碼寫入文字檔,有兩種方法:
   // 第一種辦法:用 Stream 類寫入已經按照指定編碼轉化好的位元組串
   StreamWriter sw = new StreamWriter("1.txt");
   sw.Write(chars);
   sw.Close();
   // 第二種辦法:構造指定編碼的 Writer 來寫入字串
   StreamWriter sw2 = new StreamWriter("2.txt",false,gb);
   sw2.Write(str);
   sw2.Close();
   /* 最後得到的 1.txt 和 2.txt 都是 7 個位元組 */  }
 }
}

using System;
using System.Text;
namespace WrongCode
{
 class Class1
 {
  static void Main(string[] args)
  {
   //字串類 String 中的內容是 UNICODE 字串:
   string str = "中國人123";
   // 按照 GB2312 得到位元組(得到多位元組字串)
   Encoding Client=Encoding.GetEncoding("gb2312");
   byte[] bytes = Client.GetBytes(str);
    //服務端按照gb2312正確解碼
   Encoding ServerOK = Encoding.GetEncoding("gb2312");
   string strServer = ServerOK.GetString(bytes);
   Console.WriteLine("正確轉換後的字串為:"+strServer);
   //服務端按照Unicode錯誤解碼
   strServer = Encoding.Unicode.GetString(bytes);
   Console.WriteLine("錯誤轉換後的字串為:"+strServer);
  }
 }
}

using System;
using System.Text;
namespace WrongCode
{
 class Class1
 {
    static void Main(string[] args)
  {
   //字串類 String 中的內容是 UNICODE 字串:
   string str = "中國人123";
   // 按照 GB2312 得到位元組(得到多位元組字串)
   Encoding Client=Encoding.GetEncoding("gb2312");
   byte[] bytes = Client.GetBytes(str);   
   //服務端按照gb2312正確解碼
   Encoding ServerOK = Encoding.GetEncoding("gb2312");
   string strServer = ServerOK.GetString(bytes);
   Console.WriteLine("正確轉換後的字串為:"+strServer);
   //服務端按照Unicode錯誤解碼
   strServer = Encoding.Unicode.GetString(bytes);
   Console.WriteLine("錯誤轉換後的字串為:"+strServer);
  }
 }
}


  private void Page_Load(object sender, System.EventArgs e)
  {
   Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
   if (!Page.IsPostBack)
   {
    Response.Write("還沒有輸入任何字元!<br><br>");
   }
   else
   {
    Label_1.Text="";
    Label_2.Text="";
    Label_0.Text=Convert.ToString((TextBox_1.Text).Length);
    //ASCII編碼輸出
    ByteFunction(TextBox_1.Text);
    //字元碼輸出
    CharFunction(TextBox_1.Text);
    //HTML編碼輸出
    HtmlFunction(TextBox_1.Text);
    GB2312Function("");
   }
  }
  //ASCII編碼輸出函數
  void ByteFunction(string str)
  {
   Byte[] MyBytes=System.Text.Encoding.ASCII.GetBytes(str);
   for (int i=0;i<str.Length;i++)
   {
    Label_2.Text+=Convert.ToString(MyBytes[i])+" ";
   }
  }
  //字元碼輸出函數
  void CharFunction(string str)
  {
   Byte[] MyBytes=System.Text.Encoding.ASCII.GetBytes(str);
   Char[] MyChars=System.Text.Encoding.ASCII.GetChars(MyBytes);
   //Label_2.Text=new string(MyChars);
   for (int i=0;i<str.Length;i++)
   {
    Label_1.Text+=Convert.ToString(MyChars[i])+" ";
   }
  }
  //HTML編碼輸出函數
  void HtmlFunction(string str)
  {
   string Str_Html=(Server.HtmlEncode(str));
   Label_3.Text=Str_Html;
   Label_4.Text=Server.HtmlEncode(Str_Html);//對要在瀏覽器中顯示的字串進行編碼。
  }
  void GB2312Function(string str)
  {
   string utfinfo = "document.write(/"alert('aa你好嗎??');/");";
   string gb2312info = "";
   Encoding utf8 = Encoding.UTF8;
   Encoding gb2312 = Encoding.GetEncoding("gb2312");    
   byte[] unicodeBytes = utf8.GetBytes(utfinfo);
   byte[] asciiBytes = Encoding.Convert(utf8, gb2312, unicodeBytes); // Convert the new byte[] into a char[] and then into a string.
   char[] asciiChars = new char[gb2312.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
   gb2312.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
   gb2312info = new string(asciiChars);
   Label_5.Text=gb2312info;
  }

生產文字驗證碼
  private void Page_Load(object sender, System.EventArgs e)
  {
   //擷取GB2312編碼頁(表)
   Encoding gb=Encoding.GetEncoding("gb2312");
 //調用函數產生4個隨機中文漢字編碼
   object[] bytes=CreateRegionCode(4); 
   //根據漢字編碼的位元組數組解碼出中文漢字
   string str1=gb.GetString((byte[])Convert.ChangeType(bytes[0], typeof(byte[])));
   string str2=gb.GetString((byte[])Convert.ChangeType(bytes[1], typeof(byte[])));
   string str3=gb.GetString((byte[])Convert.ChangeType(bytes[2], typeof(byte[])));
   string str4=gb.GetString((byte[])Convert.ChangeType(bytes[3], typeof(byte[])));
   string strKey = str1+str2+str3+str4;
   Session["regcode"] = strKey;
   byte[] data = gb.GetBytes(strKey);
   Response.ContentEncoding = gb;
   Response.OutputStream.Write(data,0,data.Length);
  }
  /*
  此函數在漢字編碼範圍內隨機建立含兩個元素的十六進位位元組數組,每個位元組數組代表一個漢字,並將
  四個位元組數組儲存在object數組中。
  參數:strlength,代表需要產生的漢字個數
  */
  public static object[] CreateRegionCode(int strlength)
  {
   //定義一個字串數組儲存漢字編碼的組成元素
   string[] rBase=new String [16]{"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
   Random rnd=new Random();
   //定義一個object數組用來
   object[] bytes=new object[strlength];
   /**//*每迴圈一次產生一個含兩個元素的十六進位位元組數組,並將其放入bject數組中
每個漢字有四個區位碼組成
區位碼第1位和區位碼第2位作為位元組數組第一個元素
區位碼第3位和區位碼第4位作為位元組數組第二個元素
*/
   for(int i=0;i<strlength;i++)
   {
    //區位碼第1位
    int r1=rnd.Next(11,14);
    string str_r1=rBase[r1].Trim();
    //區位碼第2位
    rnd=new Random(r1*unchecked((int)DateTime.Now.Ticks)+i);//更換隨機數發生器的種子避免產生重複值
     int r2;
    if (r1==13)
    {
     r2=rnd.Next(0,7);
    }
    else
    {
     r2=rnd.Next(0,16);
    }
    string str_r2=rBase[r2].Trim();
    //區位碼第3位
    rnd=new Random(r2*unchecked((int)DateTime.Now.Ticks)+i);
    int r3=rnd.Next(10,16);
    string str_r3=rBase[r3].Trim();
    //區位碼第4位
    rnd=new Random(r3*unchecked((int)DateTime.Now.Ticks)+i);
    int r4;
    if (r3==10)
    {
     r4=rnd.Next(1,16);
    }
    else if (r3==15)
    {
     r4=rnd.Next(0,15);
    }
    else
    {
     r4=rnd.Next(0,16);
    }
    string str_r4=rBase[r4].Trim();
    //定義兩個位元組變數儲存產生的隨機漢字區位碼
    byte byte1=Convert.ToByte(str_r1 + str_r2,16);
    byte byte2=Convert.ToByte(str_r3 + str_r4,16);
    //將兩個位元組變數儲存在位元組數組中
    byte[] str_r=new byte[]{byte1,byte2};
    //將產生的一個漢字的位元組數組放入object數組中
    bytes.SetValue(str_r,i);
   }
   return bytes;
  }
}

映像儲存到XML中
  private void btnUpload_Click(object sender, System.EventArgs e)
  {
   //得到使用者要上傳的檔案名稱
   string strFilePathName = loFile.PostedFile.FileName;
   string strFileName = Path.GetFileName(strFilePathName);
   int FileLength = loFile.PostedFile.ContentLength;
   if(FileLength<=0)
    return;
   try
   {
    Byte[] FileByteArray = new Byte[FileLength]; //圖象檔案臨時儲存Byte數組
    Stream StreamObject = loFile.PostedFile.InputStream; //建立資料流對像
    //讀取圖象檔案資料,FileByteArray為資料儲存體,0為資料指標位置、FileLnegth為資料長度
    StreamObject.Read(FileByteArray,0,FileLength);
    string fileName = Server.MapPath(".//WriteXml.xml");   //要開啟的檔案   
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(fileName);
    XmlNode root=xmlDoc.SelectSingleNode("dbImage");//尋找<dbGuest>
    XmlNodeList xnl=xmlDoc.SelectSingleNode("dbImage").ChildNodes;
    int nIndex = xnl.Count;
    //以下添加新結點
    XmlElement xe1=xmlDoc.CreateElement("Image");//建立一個<User>節點
    XmlElement xesub1=xmlDoc.CreateElement("ImageID");
    xesub1.InnerText=nIndex.ToString();//設定文本節點
    xe1.AppendChild(xesub1);//添加到<User>節點中
    XmlElement xesub2=xmlDoc.CreateElement("ImageContentType");
    xesub2.InnerText=loFile.PostedFile.ContentType;
    xe1.AppendChild(xesub2);
    XmlElement xesub3=xmlDoc.CreateElement("ImageSize");
    xesub3.InnerText=FileLength.ToString();
    xe1.AppendChild(xesub3);
    XmlElement xesub4=xmlDoc.CreateElement("ImageDescription");
    xesub4.InnerText=tbDescription.Text;
    xe1.AppendChild(xesub4);
    XmlElement xesub5=xmlDoc.CreateElement("ImageData");    
    xesub5.InnerText= Convert.ToBase64String(FileByteArray);
    xe1.AppendChild(xesub5);
    root.AppendChild(xe1);//添加到<dbGuest>節點中
    xmlDoc.Save(fileName);
    Response.Redirect("ShowAllImg.aspx");
   }
   catch
   {
   }
  }
  private void Page_Load(object sender, System.EventArgs e)
  {
   string fileName = Server.MapPath("./WriteXml.xml");   //要開啟的檔案
   DataSet ds = new DataSet();
   ds.ReadXml(fileName);
   dgShow.DataSource = ds.Tables["image"].DefaultView;
   dgShow.DataBind();
  }
private void Page_Load(object sender, System.EventArgs e)
  {
   int ImgID = Convert.ToInt32(Request.QueryString["ID"]); //ID為圖片ID
   //建立資料庫連結
   string fileName = Server.MapPath(".//WriteXml.xml");   //要開啟的檔案   
   XmlDocument xmlDoc = new XmlDocument();
   xmlDoc.Load(fileName);
   XmlNodeList node =  xmlDoc.SelectSingleNode("//Image[ImageID='"+ImgID.ToString()+"']").ChildNodes;
   if(node!=null)
   {
    string strType = node.Item(1).InnerText;
    string strData =node.Item(4).InnerText;
    int nSize = int.Parse(node.Item(2).InnerText);
    Response.ContentType = strType;//設定輸出檔案類型
    //輸出圖象檔案位元制
    Response.OutputStream.Write(Convert.FromBase64String(strData), 0, nSize);
    Response.End();
    //也可以儲存為映像
    //   FileStream fs = new FileStream(@"C:/aa.BMP", FileMode.OpenOrCreate, FileAccess.Write);
    //   fs.Write((Convert.FromBase64String(strData), 0,nSize);
    //   fs.Close();
 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.