2

Ok, So I am writing another program for the purpose of manipulating binary files. This program is importing a file larger than anything I have had to manipulate before, about 12K.

I'm curious as to how the Stream.read command works....I know that this sounds elementary, but how can I tell that the file has been read completely so that I can begin manipulating it, as of right now I have this code...

// 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);
    } 
}

I Understand that this is very very simple, but can someone explain to me how stream.Read works, does it store everything into the byte array "data" and then I can manipulate that as I see fit, or do I have to manipulate the file as it is being read. Again I apologize if this is elementary, all thoughts are appreciated

1

2 Answers 2

7

This line

stream.Read(data, 0, size); 

reads everything from the stream and stores the file content in your byte array
You can start working immediately on the array.

See FileStream.Read docs on MSDN

Your code reads the length of the file, allocate a byte array of the correct size, then reads everything in a single shot.
Of course this method is not viable if your file is really big.
(and the definition of 'big' could be different compared to the available memory). In that case the approach used is to read chunks of the file, processing and looping till all the bytes are read.

However, DotNet has specialized classes for reading and writing binary files.
See the documentation on BinaryReader

3
  • So from what I'm looking at, it automatically reads and stores it for you, leaving the array for manipulation?
    – Bubo
    Aug 8, 2012 at 20:59
  • also in regards to bytecounter it's defined earlier in the code,
    – Bubo
    Aug 8, 2012 at 21:05
  • Yes, you get the length of the file, allocate a byte of the correct size, then read everything in a single shot. (Added some thoughts to my answer)
    – Steve
    Aug 8, 2012 at 21:08
3

This doesn't exactly answer your question as to how Stream.Read works but does illuminate the fact that what you want already exists in .Net.

File.ReadAllBytes would work without issue for a 12K file.

byte[] content = File.ReadAllBytes("path");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.