當檔案讀取或Socket讀取資料時,經常使用Stream 類別。若要將Stream 直接轉換成 String 似乎有些困難,經過一層 [] 就可輕鬆完成
/// <summary>
/// 將 Byte[] 轉為 Stream
/// </summary>
/// <returns>Stream</returns>
public static Stream BytesToStream(byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}
public static Stream BytesToStream(byte[] bytes, int Length)
{
Stream stream = new MemoryStream(bytes, 0, Length);
return stream;
}
/// <summary>
/// 將 Stream 轉為 Byte[]
/// </summary>
public static byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
/*將 stream 指針指向開頭*/
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
沒有留言:
張貼留言