C#网络编程之编码解码
这里是代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Windows; 7 using System.Windows.Controls; 8 using System.Windows.Data; 9 using System.Windows.Documents; 10 using System.Windows.Input; 11 using System.Windows.Media; 12 using System.Windows.Media.Imaging; 13 using System.Windows.Navigation; 14 using System.Windows.Shapes; 15 16 namespace WpfApplication1 17 { 18 /// <summary> 19 /// MainWindow.xaml 的交互逻辑 20 /// </summary> 21 public partial class MainWindow : Window 22 { 23 public MainWindow() 24 { 25 InitializeComponent(); 26 } 27 28 private void Button_Click_1(object sender, RoutedEventArgs e) 29 { 30 textBlock1.Text = ""; 31 EncodingInfo[] n = Encoding.GetEncodings(); 32 foreach (EncodingInfo item in n) 33 { 34 Encoding en = item.GetEncoding(); 35 textBlock1.Text += string.Format("编码名称:{0,-18},编码描述:{1}\n", en.HeaderName, en.EncodingName); ; 36 } 37 } 38 39 private void Button_Click_2(object sender, RoutedEventArgs e) 40 { 41 textBlock1.Text = ""; 42 Encoding utf8 = Encoding.UTF8; 43 textBlock1.Text = string.Format("编码名称:{0},编码描述:{1}",utf8.HeaderName,utf8.EncodingName); 44 45 } 46 47 private void Button_Click_3(object sender, RoutedEventArgs e) 48 { 49 textBlock1.Text = ""; 50 string s = "abcd"; 51 Encoding unicode = Encoding.Unicode; 52 Encoding utf8 = Encoding.UTF8; 53 byte[] b = Encoding.Convert(unicode,utf8,unicode.GetBytes(s)); 54 string s1 = utf8.GetString(b); 55 textBlock1.Text = "转码前:"+s+"\n 转码后:"+s1; 56 } 57 58 private void Button_Click_4(object sender, RoutedEventArgs e) 59 { 60 textBlock1.Text=""; 61 Encoding en = Encoding.GetEncoding("gb2312"); 62 //开始编码 63 byte[] b = en.GetBytes("abcd"); 64 //显示编码后的信息 65 textBlock1.Text ="abcd编码后:"+ BitConverter.ToString(b); 66 //解码 67 textBlock1.Text += "\n 解码后:"+en.GetString(b); 68 } 69 } 70 }