繁体   English   中英

如何使用C#中的StreamReader从特定位置读取文件?

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

我有一个文本文件,我想从文件的特定到结尾读取此文本文件。

我可以通过以下方式做到这一点。

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

但我希望这只能使用StreamReader来完成。

我这样做,但它没有给出正确的结果。

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

我也可以通过以下方式做到这一点。 但我想避免for循环。

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

我的问题根本不重复,前一个是关于阅读所有文件,但我的问题是从特定行读到最后。

你只需要行 - Skip(1).Take(2)采取Skip(1).Take(2) - 为什么不直接读它们?

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

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

    ...
  }

请注意,您使用StreamReader当前代码等于Skip(2).Take(1).First() 一般情况下 - Skip(M).Take(N) - ,你必须使用for循环(或他们的仿真):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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