Convert.ToBase64String(Byte[])和Encoding.UTF8.GetString(Byte[])

二者都是规定一种编码,让各个调用方遵守这个规则,这样可以在他们之间正确的传递数据.

----- 将byte[]转换成string

Convert.ToBase64String将 8 位无符号整数数组的值转换为其用 Base64 数字编码的等效字符串表示形式。

Encoding.GetString将指定字节数组中的一个字节序列解码为一个字符串。 

两个MSDN的例子

C# code
?
1
2
3
4
5
6
7
private  string  ReadAuthor(Stream binary_file) {
   System.Text.Encoding encoding = System.Text.Encoding.UTF8;
   // Read string from binary file with UTF8 encoding
   byte [] buffer =  new  byte [30];
   binary_file.Read(buffer, 0, 30);
   return  encoding.GetString(buffer);
}

C# code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public  void  EncodeWithString() {
    System.IO.FileStream inFile;    
    byte []             binaryData;
 
    try  {
       inFile =  new  System.IO.FileStream(inputFileName,
                                 System.IO.FileMode.Open,
                                 System.IO.FileAccess.Read);
       binaryData =  new  Byte[inFile.Length];
       long  bytesRead = inFile.Read(binaryData, 0,
                            ( int )inFile.Length);
       inFile.Close();
    }
    catch  (System.Exception exp) {
       // Error creating stream or reading from it.
       System.Console.WriteLine( "{0}" , exp.Message);
       return ;
    }
 
    // Convert the binary input into Base64 UUEncoded output.
    string  base64String;
    try  {
        base64String = 
          System.Convert.ToBase64String(binaryData, 
                                 0,
                                 binaryData.Length);
    }
    catch  (System.ArgumentNullException) {
       System.Console.WriteLine( "Binary data array is null." );
       return ;
    }
 
    // Write the UUEncoded version to the output file.
    System.IO.StreamWriter outFile; 
    try  {
       outFile =  new  System.IO.StreamWriter(outputFileName,
                            false ,
                            System.Text.Encoding.ASCII);          
       outFile.Write(base64String);
       outFile.Close();
    }
    catch  (System.Exception exp) {
       // Error creating stream or writing to it.
       System.Console.WriteLine( "{0}" , exp.Message);
    }
}

Encoding.UTF8.GetString是针对使用utf8编码得到的字符串对应的byte[]使用,可以还原我们能看懂的字符串,
而Convert.ToBase64String是对任意byte[]都可使用,得到的是用字符串表示的byte[]信息 内容类似"Jwl9Kh+lPfmSPio//UpvbA=="


Base64有个优点,就是可以用文本格式传输,base64绝对不存在任何不可读的字符,也不存在关键字冲突字符,不需要转义。
缺点:Base64比起的它的原始文本增大约30%。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值