Convert a ByteArray into a Stream

Often when you need to call a function to save a file to disk or to a database you are required to pass a .NET stream to the function but all you have is a byte array. In pre-.NET days you had to move streams bit by bit by using byte arrays. You had to manage the whole process. Fortunately that is no longer the case. The System.IO namespace has several objects that allow us to deal with streams (many of which inherit the Stream object).

Simple conversions:

ByteArray to Stream (C#):

Stream s = new MemoryStream(<>);

Example saving ByteAray to disk (C#):
(make sure you include: using System.IO;)

byte[] arr = <>;

Stream s = new MemoryStream(arr);
StreamReader sr = new StreamReader(s);
StreamWriter sw = new StreamWriter(@”C:\uploads\demo.txt”);
sw.Write(sr.ReadToEnd());
sr.Close();
sw.Close();


Categories: Misc

Tags: , , ,

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: