[英]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:
br是我的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. 编辑:好吧,我认为这是因为Binary Reader的BaseStream长度很长,但它的读者需要int32计数。 If I cast the 64s into 32s, is it possible I will lose bytes in larger files?
如果我将64s转换为32s,是否有可能在较大的文件中丢失字节?
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
. 您的代码无法编译,因为BaseStream的Length属性的类型为
long
但您尝试将其用作int
。 Implicit casting which might lead to data loss is not allowed so you have to cast it to int
explicitly. 不允许隐式转换可能导致数据丢失,因此您必须明确地将其强制转换为
int
。
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
看看这个问题以及Jon Skeet建议的解决方案
BinaryReader.ReadBytes returns a byte[]. BinaryReader.ReadBytes返回一个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: 如果你想从文件中读取所有字节,那么File类中有一个方便的方法:
http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes.aspx 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. PS:你应该重复读取大块文件的字节块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.