二者都是规定一种编码,让各个调用方遵守这个规则,这样可以在他们之间正确的传递数据.
----- 将byte[]转换成string
Encoding.GetString将指定字节数组中的一个字节序列解码为一个字符串。
两个MSDN的例子
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);
}
|
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%。