Get the App
SLTechnology News&Howtos  ›  Network Security  › 

C # Stream and byte [], file conversion

Shulou Source: shulou.com Published: 2022-06-01 03:47:47 10月04日 Update

/* - - - - - - - - - - - - - - - - - - - - - - - -

* 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;

}

Tags: File between location C # Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Shulou Tech Info Redmi Shulou Information macOS