C # - Creating an array of bytes of unknown size?

I am trying to create a class to control the opening of a specific file. I would like one of the properties to be a byte array of the file, but I don't know how big the file will be. I tried declaring an array of bytes as:

public byte[] file; 

... but that will not allow me to install it the way I tried. br my BinaryReader:

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

None of the methods work. I assume this because I did not initialize the byte array, but I do not want to give it a size if I do not know the size. Any ideas?

edit: Okay, I think because the length of the Binary Reader BaseStream is long, but its readers take int32. If I transfer 64s to 32s, is it possible that I will lose bytes in large files?

+4
source share
3 answers

I had no problems reading the 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 does not compile because the Length BaseStream property is of type long , but you are trying to use it as an int . Implicit casting, which can lead to data loss, is not allowed, so you must explicitly point it to an int .

Update

Just keep in mind that the code above is intended to emphasize your original problem and should not be used as it is. Ideally, you should use a buffer to read the stream in chunks. Take a look at this question and the solution proposed by John Skeet

+4
source

BinaryReader.ReadBytes returns byte []. There is no need to initialize an array of bytes, because this method already does this inside and returns a full array.

If you want to read all bytes from a file, there is a convenient method in the File class:

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

+1
source

You cannot create an unknown array size.

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

PS: you will need to read byte chunks for large files multiple times.

0
source

Source: https://habr.com/ru/post/1387844/


All Articles