C # Stream and byte [], file conversion
/* - - - - - - - - - - - - - - - - - - - - - - - -
* Conversion between Stream and byte[]
* - - - - - - - - - - - - - - - - - - - - - - - */
///
///convert Stream to byte[]
///
public byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
//Set the current stream position to the start of the stream
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
///
///convert byte[] to Stream
///
public Stream BytesToStream(byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}
/* - - - - - - - - - - - - - - - - - - - - - - - -
* Conversion between Stream and File
* - - - - - - - - - - - - - - - - - - - - - - - */
///
///Write Stream to File
///
public void StreamToFile(Stream stream,string fileName)
{
//convert Stream to byte[]
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
//Set the current stream position to the start of the stream
stream.Seek(0, SeekOrigin.Begin);
//write byte[] to file
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(bytes);
bw.Close();
fs.Close();
}
///
///Read Stream from File
///
public Stream FileToStream(string fileName)
{
//Open file
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
//read byte of file []
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
//convert byte[] to Stream
Stream stream = new MemoryStream(bytes);
return stream;
}