C# 将 UTF-8 转换为 base64 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13938137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert UTF-8 to base64 string
提问by Nicolas Voron
I'm trying to convert UTF-8to base64string.
我正在尝试转换UTF-8为base64字符串。
Example: I have "abcdef==" in UTF-8. It's in fact a "representation" of a base64string.
示例:我在UTF-8. 它实际上是一个base64字符串的“表示” 。
How can I retrieve a "abcdef==" base64string (note that I don't want a "abcdef==" "translation" from UTF-8, I want to get a string encoded in base64which is"abcdef==").
我怎样才能检索“ABCDEF ==”base64字符串(请注意,我不希望有一个“ABCDEF ==”“翻译”的UTF-8,我想编码的字符串base64,其是“ABCDEF ==”)。
EDIT
As my question seems to be unclear, here is a reformulation:
编辑
因为我的问题似乎不清楚,这里是一个重新表述:
My byte array (let's say I name it A) is represented by a base64string. Converting A to base64gives me "abcdef==".
我的字节数组(假设我将其命名为 A)由一个base64字符串表示。将 A 转换为base64给我“abcdef==”。
This string representation is sent through a socket in UTF-8 (note that the string representation is exactly the same in UTF-8 and base64). So I receive an UTF-8 message which contains "whatever/abcdef==/whatever" in UTF-8.
此字符串表示通过 UTF-8 中的套接字发送(请注意,字符串表示在 UTF-8 和 base64 中完全相同)。所以我收到一条 UTF-8 消息,其中包含 UTF-8 中的“whatever/abcdef==/whatever”。
So I need to retrieve the base64 "abcedf==" string from this socket message in order to get A.
所以我需要从这个套接字消息中检索 base64 "abcedf==" 字符串以获得 A.
I hope this is more clear!
我希望这更清楚!
采纳答案by Iridium
It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decodedis abcdef==, the following should work:
很难说出您要实现的目标,但假设您要获取解码时为的 Base64 字符串abcdef==,则以下内容应该有效:
byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);
This will output: YWJjZGVmPT0=which is abcdef==encoded in Base64.
这将输出:YWJjZGVmPT0=其abcdef==在Base64编码。
Edit:
编辑:
To decode a Base64 string, simply use Convert.FromBase64String(). E.g.
要解码 Base64 字符串,只需使用Convert.FromBase64String(). 例如
string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);
At this point, byteswill be a byte[](not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:
此时,bytes将是一个byte[](不是一个string)。如果我们知道字节数组表示 UTF8 中的字符串,则可以使用以下方法将其转换回字符串形式:
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);
This will output the original input string, abcdef==in this case.
abcdef==在这种情况下,这将输出原始输入字符串。

