how can i jump into some line in my file, e.g line 300 in c:\text.txt?
+10
A:
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
}
Darin Dimitrov
2010-01-20 17:01:45
@Darin Dimitrov: "Now you are at line 300. You may continue reading." Be careful if there are less than 300 lines!
Jason
2010-01-20 17:19:18
@Jason, I intentionally omitted exception handling to demonstrate the process of *jumping to a line* in a file. The original question was not how to write production ready code that I can copy-paste that will jump to a line in a file. There are many other things that we must take care of such as verify file existence, verify that the account our process executes under has read permissions on the file, log errors, etc...
Darin Dimitrov
2010-01-20 17:24:06
Whoa, it's a big leap from pointing out that your comment is slightly misleading to interpreting my comment as if I'm saying that is not safe for use in production.
Jason
2010-01-20 17:31:37
A:
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];
Joel Etherton
2010-01-20 17:01:45
+7
A:
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());
}
}
Jason
2010-01-20 17:04:24
A:
/// <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();
}
}
Jeffrey L Whitledge
2010-01-20 17:18:11
A:
A couple things I noticed:
Microsoft's sample usage of the StreamReader constructor checks whether the file exists first.
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.");
}
David
2010-01-20 18:49:14