跳转到文件行c#

时间:2010-01-20 16:59:09

标签: c# .net file-io

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

5 个答案:

答案 0 :(得分:12)

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
}

答案 1 :(得分: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();
        }
    }

用法:

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

简单方法:

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

答案 2 :(得分:1)

Dim arrText() As String 
Dim lineThreeHundred As String

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

lineThreeHundred = arrText(299) 

编辑:C#版本

string[] arrText;
string lineThreeHundred;

arrText = File.ReadAllLines("c:\test.txt");
lineThreeHundred = arrText[299];

答案 3 :(得分:1)

我注意到了几件事:

  1. Microsoft的sample usage of the StreamReader constructor检查 该文件是否首先存在。

  2. 你应该通过一个通知用户 屏幕上或日志中的消息,如果 该文件不存在或是 比我们预期的要短。这让我们 你知道任何意外的 错误,如果他们发生的话 调试系统的其他部分。 我意识到这不是你的一部分 原来的问题,但这是一个很好的 实践。

  3. 所以这是其他几个答案的组合。

    string path = @"C:\test.txt";
    int count = 0;
    
    if(File.Exists(path))
    {
      using (var reader = new StreamReader(@"c:\test.txt"))
      {
        while (count < 300 && reader.ReadLine() != null)
        {
          count++;
        }
    
        if(count != 300)
        {
          Console.WriteLine("There are less than 300 lines in this file.");
        }
        else
        {
          // keep processing
        }
      }
    }
    else
    {
      Console.WriteLine("File '" + path + "' does not exist.");
    }
    

答案 4 :(得分:0)

/// <summary>
/// Gets the specified line from a text file.
/// </summary>
/// <param name="lineNumber">The number of the line to return.</param>
/// <param name="path">Identifies the text file that is to be read.</param>
/// <returns>The specified line, is it exists, or an empty string otherwise.</returns>
/// <exception cref="ArgumentException">The line number is negative, or the path is missing.</exception>
/// <exception cref="System.IO.IOException">The file could not be read.</exception>
public static string GetNthLineFromTextFile(int lineNumber, string path)
{
    if (lineNumber < 0)
        throw new ArgumentException(string.Format("Invalid line number \"{0}\". Must be greater than zero.", lineNumber));
    if (string.IsNullOrEmpty(path))
        throw new ArgumentException("No path was specified.");

    using (System.IO.StreamReader reader = new System.IO.StreamReader(path))
    {
        for (int currentLineNumber = 0; currentLineNumber < lineNumber; currentLineNumber++)
        {
            if (reader.EndOfStream)
                return string.Empty;
            reader.ReadLine();
        }
        return reader.ReadLine();
    }
}