简体   繁体   中英

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM