Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileStream Read/Write

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

like image 486
Bubo Avatar asked Mar 04 '26 06:03

Bubo


2 Answers

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

like image 121
Steve Avatar answered Mar 06 '26 20:03

Steve


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");
like image 26
Austin Salonen Avatar answered Mar 06 '26 20:03

Austin Salonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!