Skip to content

Convert a File into a Byte of Array

July 5, 2010

Precondition:
There are 2 examples that I describe in this post. First, is convert a file to a byte of array using BinaryFormatter and the second is using File.ReadAllBytes.

Example 1:
Using BinaryFormatter

I make a function that receive the address of the file and return a bye of array
function byte[] ConvertFileToByteArray_1 (string path)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream msx = new MemoryStream();
bf.Serialize(msx, path);
msx.Seek(0, 0);
byte[] sender= msx.ToArray();
msx.Close();
return sender;
}

Example 2:
Using File.ReadAllBytes

I make a function that receive the address of the file and return a bye of array
function byte[] ConvertFileToByteArray_2 (string path)
{
byte[] sender= File.ReadAllBytes(path);
return sender;
}

Further explanation:
these are the value of functions’ parameter can be processed:

string path = string.Format(@"C:\Documents and Settings\xxx\Desktop\xxxx.htm");

or

string path= string.Format("{0}\\{1}.htm",directory, xxxx"));

where directory can be written like this above

string directory = string.Format("C:\\Documents and Settings\\xxx\\Desktop");

The path above means that xxx is your current System User and the xxxx is your file’s name. The htm is an ordinary extension, you can replace it by pdf or doc or something else, just based on your needs.
And don’t forget to give security to your file.
My suggestion is just add user ‘Everyone’ and ‘Full Control’ permission.

Leave a Comment

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.