1

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?

Tom
  • 71
  • 1
  • 2
  • 11
  • you can try to put read func inside a loop, so every second or minute you will read a file – Donald Wu Feb 16 '17 at 06:07
  • 1
    See [FileStream.Read()](https://msdn.microsoft.com/en-us/library/system.io.filestream.read(v=vs.110).aspx) – Mike Hixson Feb 16 '17 at 06:12
  • @CodeCaster Sorry for the previously cocky answer. "1024 bytes of text" was just an example and I primarily use this when sending data over sockets hence why only certain bits of a file can be sent at a time(instead of 100mb of data or something ridiculous like that). I see where you're coming from, how would we go about fixing that though? – Tom Feb 16 '17 at 10:22
  • 2
    No problem. It all depends on what you want to do exactly. If you append all bytes at the other end again _before_ turning the bytes back into a string, which I now realise the accepted answer does, the issue disappears. You don't want to have a 100 MB string in memory at once though. – CodeCaster Feb 16 '17 at 11:58

1 Answers1

3

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();
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88