Search code examples
c#pythonfilebytestream

Is it possible to read a certain amount of a file each time?


In C# is it possible to read only a certain amount of bytes of data from a file every time read is executed? It would accomplish the same thing as the python line of code below

data=file.read(1024)

Where 1024 is the amount of bytes it reads.

data would return a string containing 1024 bytes of text from the file.

Is there something for C# that can accomplish the same thing?


Solution

  • You read the file in 1024 byte chunks like this:

    string fileName = @"Path to the File";
    int bufferCapacity = 1024;
    using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
    {
       var buffer = new byte[bufferCapacity ]; // will contain the first 1024 bytes
       fs.Read(buffer, 0, bufferCapacity);
    }
    

    Finally the buffer will contain the required bytes, to convert them to a string you can use the following line of code:

    var stringData = System.Text.Encoding.UTF8.GetString(buffer);
    

    Additional note for you, if you need to get the first n Lines from a file means you can use the following line:

     List<string> firstNLines = File.ReadLines(fileName).Take(n).ToList();