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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: