Converting a File to byte[]


In a previous post I had talked about how I was thinking about embedding files into my program by just declaring them as byte[] arrays and using the data within these arrays as a way to compile the information straight into my EXE. Of course using an embedded resource in C# would be better (which I outlined in an earlier entry), but I thought a program like this could also come in handy when working with routines that parse I/O input.

I ran into a situation like this when I was writing an application to work with ID3 tags in an mp3. I didn’t want to have to keep specifying the file each time I ran my test application, nor did I have the I/O code completed yet. This allowed me to simulate the data and feed it into my routine as if it were pulled from a file.

Well, after taking a little bit of time trolling Google, I was unable to locate a program that could do this quickly. So I decided to create a quick one myself. I figure I might not be the only person on the entire Internet looking for such an application.

It’s a very, very simple program that will take the file you specify, read it’s contents, and create a byte[] array which you can simply just drop into your C# source code and use. An example of it’s output would be:

[csharp]byte[] byFileData = new byte[] { 71, 73, 70, 56, 57, 97, 20, 0, 22, 0 };[/csharp]

Screen Shot:

FileTobyte Screen Shot
Download Program: FileToByte Executable

Download Source Code: FileToByte Source Code

  1. #1 by Colonel on January 21, 2007 - 10:11 PM

    Why on earth would you want to use this method to embed files in your code? .Net has .ResX files for a reason, and you can use them in a OO way (like MyNameSpace.Resourses.SomeBinaryFile; which is already a byte[] for you).

  2. #2 by eric on January 22, 2007 - 6:22 AM

    Colonel,

    No doubt that using Embedded Resources in C# is better than the method I outlined above, but I’m not going to use the blanket statement that says Embedded Resources is for everyone.

    My above method only offers an alternative solution.

(will not be published)