字符串,字节数组,流之间的转换

1 byte[]与string之间的转换

string str1 = "123456";
byte[] buffer1 = System.Text.Encoding.ASCII.GetBytes(str1);
Stream stream = new MemoryStream(buffer1);
//return stream;
string str2 = System.Text.Encoding.ASCII.GetString(buffer1);
byte[] buffer2 = new byte[stream.Length];
stream.Read(buffer2,0,(int)stream.Length);
string str3 = System.Text.Encoding.ASCII.GetString(buffer2);
stream.Flush();
stream.Close();


2 base64字符串与byte[]的转换

/// <summary>
/// 把byte[]转成base64编码
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string ByteToBase64String(this byte[] bytes)
{
var base64Str = Convert.ToBase64String(bytes);
return base64Str;
}


/// <summary>
/// 从base64字符转byte[]
/// </summary>
/// <param name="base64Str"></param>
/// <returns></returns>
public static byte[] Base64StringToByte(this string base64Str)
{
var myByte = Convert.FromBase64String(base64Str);
return myByte;
}