C# - Creating byte array of unknown size?

30,868

Solution 1

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

Solution 2

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.

Share:
30,868
mowwwalker
Author by

mowwwalker

Updated on December 24, 2020

Comments

  • mowwwalker
    mowwwalker over 3 years

    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?