Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read file from specific position using StreamReader in C#?

Tags:

c#

I have a text file and I want to read this text file from a particular till end of file.

I can do this by the following way.

string path = @"C:\abc.txt";
var pp = File.ReadAllLines(path).Skip(1).Take(2);

But I want this to be done using StreamReader only.

I'm doing this, but its not giving proper result.

using (Stream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
        using (StreamReader streamReader = new StreamReader(stream))
        {
                var str = streamReader.ReadLine().Skip(1).Take(2);
        }
}

I can do this by the following way too. but I want to avoid the for loop.

using (Stream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    using (StreamReader streamReader = new StreamReader(stream))
    {
                int count=2;
                for (int i = 0; i < count; i++)
                {
                    streamReader.ReadLine();
                }
                string data = streamReader.ReadLine();
    }
}

My question is not duplicate at all, previous one is about reading all files but my question is read from specific line till end.

like image 820
vivek nuna Avatar asked Feb 25 '26 16:02

vivek nuna


1 Answers

You want just two lines - Skip(1).Take(2) - why don't read them directly?

  using (StreamReader streamReader = new StreamReader(stream)) {
    streamReader.ReadLine(); // skip the first line

    // take next two lines
    string[] data = new string[] {
      streamReader.ReadLine(),
      streamReader.ReadLine(),
    }; 

    ...
  }

Please, notice that you current code with StreamReader equals to Skip(2).Take(1).First(). In general case - Skip(M).Take(N) -, you have to use for loops (or their emulation):

   using (StreamReader streamReader = new StreamReader(stream)) {
     // Skip M first items
     for (int i = 0; i < M; ++i)
       streamReader.ReadLine();

     string[] data = new string[N];

     // Take N next items 
     for (int i = 0; i < N; ++i)
       data[i] = streamReader.ReadLine(); 
   }
like image 123
Dmitry Bychenko Avatar answered Feb 28 '26 04:02

Dmitry Bychenko



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!