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;
}
thats easier:
ReplyDeletebyte[] rawData = File.ReadAllBytes("filename");
that's easier:
ReplyDeletebyte[] rawData = File.ReadAllBytes("filename");
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.
ReplyDeleteThanks for the indactions. But what happends if the file is very large. Aren't there any problems with the buffer?
ReplyDeleteAndreea, 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.
ReplyDeleteWell, Syste,.IO.File.ReadAllBytes(fileName) first appeard in .NET2.0
ReplyDeleteKC's solution workes well on 1.1
hi.
ReplyDeletejust want to know how can I read a specific bit in a byte... thx
Hi dc, i guess you need mthod like this
ReplyDeleteprivate bool GetBit(byte b, int pos)
{
return ((b & (byte)(1 << pos)) != 0);
}
--random
I guess it would be safer to close the file stream before leaving the function.
ReplyDeleteHow do you handle large files? Files > 200M
ReplyDeleteHi. 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?
ReplyDeleteGood Job dude!
ReplyDeletehi,I am having a list of bytes.Will that be converted into File
ReplyDelete