简体   繁体   中英

How to read file from specific position using StreamReader in 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM