Bub*_*ubo 2 c# file-io stream visual-studio-2010
好的,所以我正在编写另一个程序来操作二进制文件.这个程序导入的文件大于我之前必须操作的文件,大约12K.
我很好奇Stream.read命令是如何工作的......我知道这听起来很简单,但我怎么知道文件已被完全读取以便我可以开始操作它,就像现在我一样这段代码......
// Opens a stream to the path chosen in the open file dialog
using (FileStream stream = new FileStream(chosenFile, FileMode.Open, FileAccess.Read))
{
size = (int)stream.Length; // Returns the length of the file
data = new byte[size]; // Initializes and array in which to store the file
stream.Read(data, 0, size); // Begins to read from the constructed stream
progressBar1.Maximum = size;
while (byteCounter < size)
{
int i = data[byteCounter];
byteCounter++;
progressBar1.Increment(1);
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这非常简单,但是有人可以向我解释stream.Read是如何工作的,它是否将所有内容存储到字节数组"data"中然后我可以按照我认为合适的方式操作它,或者我是否必须操纵它正在阅读的文件.我再次道歉,如果这是基本的,所有的想法都表示赞赏
这条线
stream.Read(data, 0, size);
Run Code Online (Sandbox Code Playgroud)
从流中读取所有内容并将文件内容存储在字节数组中
您可以立即开始在数组上工作.
请参阅MSDN上的FileStream.Read文档
您的代码读取文件的长度,分配正确大小的字节数组,然后一次性读取所有内容.
当然,如果您的文件非常大,这种方法是不可行的.
(与可用内存相比,'big'的定义可能不同).在这种情况下,使用的方法是读取文件的块,处理和循环,直到读取所有字节.
但是,DotNet具有用于读取和写入二进制文件的专用类.
请参阅BinaryReader上的文档