7

I'm trying to create a class to manage the opening of a certain file. I would one of the properties to be a byte array of the file, but I don't know how big the file is going to be. I tried declaring the byte array as :

public byte[] file;

...but it won't allow me to set it the ways I've tried. br is my BinaryReader:

file = br.ReadBytes(br.BaseStream.Length);

br.Read(file,0,br.BaseStream.Length);

Neither way works. I assume it's because I have not initialized my byte array, but I don't want to give it a size if I don't know the size. Any ideas?

edit: Alright, I think it's because the Binary Reader's BaseStream length is a long, but its readers take int32 counts. If I cast the 64s into 32s, is it possible I will lose bytes in larger files?

mowwwalker
  • 16,634
  • 25
  • 104
  • 157
  • To answer your second question, the files would have to be larger than two gigabytes before this becomes a problem. – Robert Harvey Dec 24 '11 at 06:55
  • @RobertHarvey - while true since this is the limit imposed by the runtime, it could become a problem with significantly smaller files due to memory pressures on the machine. – codekaizen Dec 24 '11 at 07:00
  • @Walkerneo - Note that the signature of this method allows you to make a smaller array, say of 4096 bytes, and then call it in a loop while the result of the `Read` method is the same as the number of bytes you've requested. – codekaizen Dec 24 '11 at 07:02

3 Answers3

7

I had no problems reading a file stream:

 byte[] file;
 var br = new BinaryReader(new FileStream("c:\\Intel\\index.html", FileMode.Open));
 file = br.ReadBytes((int)br.BaseStream.Length);

Your code doesn't compile because the Length property of BaseStream is of type long but you are trying to use it as an int. Implicit casting which might lead to data loss is not allowed so you have to cast it to int explicitly.
Update
Just bear in mind that the code above aims to highlight your original problem and should not be used as it is. Ideally, you would use a buffer to read the stream in chunks. Have a look at this question and the solution suggested by Jon Skeet

Community
  • 1
  • 1
Pencho Ilchev
  • 3,201
  • 18
  • 21
1

You can't create unknown sized array.

byte []file=new byte[br.BaseStream.Length];

PS: You should have to repeatedly read chunks of bytes for larger files.

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
1

BinaryReader.ReadBytes returns a byte[]. There is no need to initialize a byte array because that method already does so internally and returns the complete array to you.

If you're looking to read all the bytes from a file, there's a handy method in the File class:

http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes.aspx