Saturday, December 29, 2007

C#: Read a file into a byte array

public byte[] ReadByteArrayFromFile(string fileName)
{
byte[] buff = null;
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long numBytes = new FileInfo(fileName).Length;
buff = br.ReadBytes((int)numBytes);
return buff;
}

13 comments:

  1. thats easier:

    byte[] rawData = File.ReadAllBytes("filename");

    ReplyDelete
  2. that's easier:

    byte[] rawData = File.ReadAllBytes("filename");

    ReplyDelete
  3. Accepted it is less lines of code. But you sacrifice the ability to have more explicit control on the file like FileAccess.Read etc. But once again, both gets the job done.

    ReplyDelete
  4. Thanks for the indactions. But what happends if the file is very large. Aren't there any problems with the buffer?

    ReplyDelete
  5. Andreea, you are absolutely right. However the real question would be why at all would you want to load a file into byte[]. I do not see any apparent reason to do that for a large enough file, and of course you would have to do some memory management yourself if there is a need, may be chunk the bytes or something. Hope this clarifies.

    ReplyDelete
  6. Well, Syste,.IO.File.ReadAllBytes(fileName) first appeard in .NET2.0
    KC's solution workes well on 1.1

    ReplyDelete
  7. hi.
    just want to know how can I read a specific bit in a byte... thx

    ReplyDelete
  8. Hi dc, i guess you need mthod like this

    private bool GetBit(byte b, int pos)
    {
    return ((b & (byte)(1 << pos)) != 0);
    }

    --random

    ReplyDelete
  9. I guess it would be safer to close the file stream before leaving the function.

    ReplyDelete
  10. How do you handle large files? Files > 200M

    ReplyDelete
  11. Hi. How do you do it the other way around? I mean. Having the byte array, get the file so that a user can see it?

    ReplyDelete
  12. hi,I am having a list of bytes.Will that be converted into File

    ReplyDelete

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.