Base 64 encoding in C#

泪湿孤枕 提交于 2019-12-24 00:24:42

问题


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)));

Is this code converting my byte[] into a base 64 encoded string?

Thank you!


回答1:


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);
}



回答2:


Use the Convert.ToBase64String() method. It takes a byte array as parameter and returns the converted string.




回答3:


No, that's just converting it to a list of integers.

Use Convert.ToBase64String(). Assuming ImageBytes is a byte[]:

var base64Output = Convert.ToBase64String(ImageBytes);


来源:https://stackoverflow.com/questions/11809675/base-64-encoding-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!