跳转到文件行c#

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

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

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

现代方法:

 class LineReader : IEnumerable, IDisposable { TextReader _reader; public LineReader(TextReader reader) { _reader = reader; } public IEnumerator 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 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()); } } 

我注意到几件事:

  1. Microsoft 对StreamReader构造函数的示例用法检查文件是否首先存在。

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

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

 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."); } 
 ///  /// Gets the specified line from a text file. ///  /// The number of the line to return. /// Identifies the text file that is to be read. /// The specified line, is it exists, or an empty string otherwise. /// The line number is negative, or the path is missing. /// The file could not be read. 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(); } }