1.
将一个流转换成字符串
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WebClient wc = new WebClient();
System.IO.Stream stream = wc.OpenRead("http://localhost:34992/WebForm1.aspx");
StreamReader reader = new StreamReader(stream);
string ss = reader.ReadToEnd(); //将一个流文件转换成字符串
Response.Write(ss);
}
}
}
将一个流转换成一个二进制数组
private byte[] StreamToByte(Stream stream)
{
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
//读完后跳到开始流的开始位置
stream.Seek(0, SeekOrigin.Begin);
return buffer;
}
将一个二进制数组转换成字符串
byte[] byteB=new byte[]{};
string str= System.Text.Encoding.UTF8.GetString(byteB);
将一个字符串转换成进制数组
string str = "你好,中国";
byte[] byteB = System.Text.Encoding.UTF8.GetBytes(str);
Object与byte[]的相互转换
/// <summary>
/// 将Ojbect对象转换为byte数组
/// </summary>
/// <param name="obj">被转换对象</param>
/// <returns>转换后byte数组</returns>
public static byte[] Object2Bytes(object obj)
{
byte[] buff;
using (MemoryStream ms = new MemoryStream())
{
IFormatter iFormatter = new BinaryFormatter();
iFormatter.Serialize(ms, obj);
buff = ms.GetBuffer();
}
return buff;
}
/// <summary>
/// 将byte数组转换object成对象
/// </summary>
/// <param name="buff">被转换byte数组</param>
/// <returns>转换完成后的对象</returns>
public static object Bytes2Object(byte[] buff)
{
object obj;
using (MemoryStream ms = new MemoryStream(buff))
{
IFormatter iFormatter = new BinaryFormatter();
obj = iFormatter.Deserialize(ms);
}
return obj;
}