原文:
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;
}