C#中的Base 64编码 [英] Base 64 encoding in C#
问题描述
我继承了一些C#代码。此代码需要将图片上传到Web服务。此代码将图片的字节保存到称为 ImageBytes
的 byte []
中。为了确保最大的可移植性,我想先将 ImageBytes
编码为以64为基数的字符串。我相信下面的代码可以做到这一点,但是我不确定。有人可以验证我的假设是否正确吗?
I have inherited some C# code. This code needs to upload a picture to a web service. This code saves the bytes of picture into byte[]
called ImageBytes
. To ensure the greatest portability, I want to first encode the ImageBytes
into a base 64 encoded string. I believe the following code is doing that, however, I'm not sure. Can someone please verify if my assumption is correct?
StringBuilder sb = new StringBuilder();
this.ImageBytes.ToList<byte>().ForEach(x => sb.AppendFormat("{0}.", Convert.ToUInt32(x)));
此代码是否转换了我的 byte []
成基本的64位编码字符串?
Is this code converting my byte[]
into a base 64 encoded string?
谢谢!
推荐答案
使用方法 System.Convert.ToBase64String()
和 System.Convert.FromBase64String()
例如
use methods System.Convert.ToBase64String()
and System.Convert.FromBase64String()
for example
public static string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes = Encoding.ASCII.GetBytes(toEncode);
return Convert.ToBase64String(toEncodeAsBytes);
}
public static string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes = Convert.FromBase64String(encodedData);
return Encoding.ASCII.GetString(encodedDataAsBytes);
}
这篇关于C#中的Base 64编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!