原文:
C# Stream 和 byte[] 之间的转换
Stream 和 byte[] 之间的转换
/* - - - - - - - - - - - - - - - - - - - - - - - -
* Stream å byte[] ä¹é´ç转æ¢
* - - - - - - - - - - - - - - - - - - - - - - - */
///
/// å° Stream 转æ byte[]
///
public byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置å½åæµçä½ç½®ä¸ºæµçå¼å§
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
///
/// å° byte[] 转æ Stream
///
public Stream BytesToStream(byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}
/* - - - - - - - - - - - - - - - - - - - - - - - -
* Stream å æ件ä¹é´ç转æ¢
* - - - - - - - - - - - - - - - - - - - - - - - */
///
/// å° Stream åå ¥æ件
///
public void StreamToFile(Stream stream,string fileName)
{
// æ Stream 转æ¢æ byte[]
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置å½åæµçä½ç½®ä¸ºæµçå¼å§
stream.Seek(0, SeekOrigin.Begin);
// æ byte[] åå ¥æ件
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(bytes);
bw.Close();
fs.Close();
}
///
/// ä»æ件读å Stream
///
public Stream FileToStream(string fileName)
{
// æå¼æ件
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
// 读åæ件ç byte[]
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
// æ byte[] 转æ¢æ Stream
Stream stream = new MemoryStream(bytes);
return stream;
}
* Stream å byte[] ä¹é´ç转æ¢
* - - - - - - - - - - - - - - - - - - - - - - - */
///
/// å° Stream 转æ byte[]
///
public byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置å½åæµçä½ç½®ä¸ºæµçå¼å§
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
///
/// å° byte[] 转æ Stream
///
public Stream BytesToStream(byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}
/* - - - - - - - - - - - - - - - - - - - - - - - -
* Stream å æ件ä¹é´ç转æ¢
* - - - - - - - - - - - - - - - - - - - - - - - */
///
/// å° Stream åå ¥æ件
///
public void StreamToFile(Stream stream,string fileName)
{
// æ Stream 转æ¢æ byte[]
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置å½åæµçä½ç½®ä¸ºæµçå¼å§
stream.Seek(0, SeekOrigin.Begin);
// æ byte[] åå ¥æ件
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(bytes);
bw.Close();
fs.Close();
}
///
/// ä»æ件读å Stream
///
public Stream FileToStream(string fileName)
{
// æå¼æ件
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
// 读åæ件ç byte[]
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
// æ byte[] 转æ¢æ Stream
Stream stream = new MemoryStream(bytes);
return stream;
}