Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Creating byte array of unknown size?

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?

like image 492
mowwwalker Avatar asked Dec 24 '11 06:12

mowwwalker


2 Answers

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

like image 166
Pencho Ilchev Avatar answered Sep 22 '22 01:09

Pencho Ilchev


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.

like image 40
KV Prajapati Avatar answered Sep 19 '22 01:09

KV Prajapati