跳转到文件行c#

aha*_*ron 6 .net c# file-io

我怎么能跳进我文件中的某一行,例如c:\ text.txt中的第300行?

Dar*_*rov 13

using (var reader = new StreamReader(@"c:\test.txt"))
{
    for (int i = 0; i < 300; i++)
    {
        reader.ReadLine();
    }
    // Now you are at line 300. You may continue reading
}
Run Code Online (Sandbox Code Playgroud)

  • @Darin Dimitrov:"现在你在第300行.你可以继续阅读." 如果少于300行,请小心! (2认同)
  • @Jason,我故意省略异常处理来演示*跳转到文件中的行*的过程.最初的问题不是如何编写生产就绪代码,我可以复制粘贴,它将跳转到文件中的一行.我们必须处理许多其他事情,例如验证文件存在,验证我们的进程执行的帐户是否具有对文件的读取权限,记录错误等... (2认同)

jas*_*son 9

行分隔文件不是为随机访问而设计的.因此,您必须通过读取和丢弃必要的行数来查找文件.

现代方法:

class LineReader : IEnumerable<string>, IDisposable {
        TextReader _reader;
        public LineReader(TextReader reader) {
            _reader = reader;
        }

        public IEnumerator<string> GetEnumerator() {
            string line;
            while ((line = _reader.ReadLine()) != null) {
                yield return line;
            }
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }

        public void Dispose() {
            _reader.Dispose();
        }
    }
Run Code Online (Sandbox Code Playgroud)

用法:

// path is string
int skip = 300;
StreamReader sr = new StreamReader(path);
using (var lineReader = new LineReader(sr)) {
    IEnumerable<string> lines = lineReader.Skip(skip);
    foreach (string line in lines) {
        Console.WriteLine(line);
    }
}
Run Code Online (Sandbox Code Playgroud)

简单方法:

string path;
int count = 0;
int skip = 300;
using (StreamReader sr = new StreamReader(path)) {
     while ((count < skip) && (sr.ReadLine() != null)) {
         count++;
     }
     if(!sr.EndOfStream)
         Console.WriteLine(sr.ReadLine());
     }
}
Run Code Online (Sandbox Code Playgroud)


Joe*_*ton 1

Dim arrText() As String 
Dim lineThreeHundred As String

arrText = File.ReadAllLines("c:\test.txt") 

lineThreeHundred = arrText(299) 
Run Code Online (Sandbox Code Playgroud)

编辑:C#版本

string[] arrText;
string lineThreeHundred;

arrText = File.ReadAllLines("c:\test.txt");
lineThreeHundred = arrText[299];
Run Code Online (Sandbox Code Playgroud)