开发者

jump into file line c#

开发者 https://www.devze.com 2022-12-17 19:15 出处:网络
how can i jump into some line in my file, e.g line 开发者_开发问答300 in c:\\text.txt?using (var reader = new StreamReader(@\"c:\\test.txt\"))

how can i jump into some line in my file, e.g line 开发者_开发问答300 in c:\text.txt?


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
}


Line-delimited files are not designed for random access. Thus, you have to seek through the file by reading and discarding the necessary number of lines.

Modern approach:

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

Usage:

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

Simple approach:

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


Dim arrText() As String 
Dim lineThreeHundred As String

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

lineThreeHundred = arrText(299) 

Edit: C# Version

string[] arrText;
string lineThreeHundred;

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


A couple things I noticed:

  1. Microsoft's sample usage of the StreamReader constructor checks whether the file exists first.

  2. You ought to notify the user, via an message on screen or in a log, if the file either doesn't exist or is shorter than we expected. This lets you know about any unexpected errors, if they happen while you are debugging other parts of the system. I realize this wasn't part of your original question, but it's a good practice.

So this is a combination of several of the other answers.

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


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

精彩评论

暂无评论...
验证码 换一张
取 消