stream 與byte[] 轉換
阿新 • • 發佈:2019-02-09
//stream 轉為byte[]
public byte[] stream2byte(Stream stream)
{
byte[] buffer= new byte[stream.length];
stream.Read(buffer,0,buffer.length);
return buffer;
}
//byte[] 轉stream
public stream byte2stream(byte[] buffer)
{
stream stream= new MemoryStream(buffer);
stream.Seek(0,SeekOrigin.Begin);
//設定stream的position為流的開始
return stream;
}
//stream寫到檔案
public void stream2File(Stream stream)
{
byte[] buffer= new buffer[stream.length];
stream.Read(buffer,0,buffer.length);
FileStream fs= new FileStream(filename,FileMode.Create);
BinaryWriter writer= new BinaryWriter(fs);
writer.Writer(buffer);
writer.Close();
fs.Close();
}
//讀取檔案到stream
public Stream file2Stream(string path)
{
FileStream fs = new FileStream(path,fileMode.Open,FileAccess.Read);
byte[] buffer= new byte[fs.length];
fs.Read(buffer,0,buffer.length);
Stream stream=MemoryStream(buffer);
stream.Seek(0,seekOrigin.Begin);
return stream;
}