How to read the specified line in a text file?

Given a text file, how can I start reading an arbitrary line and nothing else in the file?

Say I have a test.txt file. How can I read line line 15 in a file?

All I saw was material containing saving the entire text file as an array of String, and then using the line number value as the line number to use from the array ... but there are some difficulties: the text file is incredibly huge, and the machine that I am coding a not entirely accurate system. Speed ​​is not a top priority, but it is definitely a serious problem.

Is there a way ONLY to read a specific line of a text file and save the result as a line?

Thank you for your feedback: The KINDA file is structured. He got 25 lines of information and then X lines of numbers, but line 17 of the first 25 has a value of X.

But then there is 1 empty line, and it is repeated as the second record in the file, and X may have a different value for each record.

What I want to do is read and save the first 25 lines as independent values, and then save the next X lines (usually around 250) as an array. Then I am going to store it in the SQL database and repeat with the NEXT record until I get to the Yth record (the number of records in the file is on line 3)

EDIT 2 : Well, I think I came to a solution based on a combination of the answers of your answers.

I will read the first 25 lines and store them as an array. I will copy the corresponding contents of the array to local variables, and then delete the first 25 lines. Then I can use the information to store the next X lines (element value 13 in the array) as an array, serialize it, save it in the database, and then delete the lines I just read.

Then I could repeat the process for each subsequent recording.

Of course, this depends on one assumption that I make that, to be honest, I'm not sure if this is true. Is it possible to delete the first n lines from a text file from C # without having to read the whole thing and overwrite it without the first n lines?

+52
string c # input file-io
Aug 11 '09 at 21:14
source share
14 answers

Editing .NET 4.0

Starting with .NET 4.0, you can directly access one line of a file. For example, to access line 15:

string line = File.ReadLines(FileName).Skip(14).Take(1).First(); 

This will return only the required string




Since you cannot predict the location (you can?) Of the i-th line in the file, you will also have to read all the previous lines. If the line number is small, this may be more efficient than the ReadAllLines method.

 string GetLine(string fileName, int line) { using (var sr = new StreamReader(fileName)) { for (int i = 1; i < line; i++) sr.ReadLine(); return sr.ReadLine(); } } 
+93
Aug 11 '09 at 21:19
source share

If each line has a fixed length, you can open a stream around it, search (bytes per line) * n in the file and read your line from there.

 using( Stream stream = File.Open(fileName, FileMode.Open) ) { stream.Seek(bytesPerLine * (myLine - 1), SeekOrigin.Begin); using( StreamReader reader = new StreamReader(stream) ) { string line = reader.ReadLine(); } } 

Alternatively, you can simply use StreamReader to read the lines until you find the one you need. Thus, more slowly, but still reading of each separate line is improved.

 using( Stream stream = File.Open(fileName, FileMode.Open) ) { using( StreamReader reader = new StreamReader(fileStream) ) { string line = null; for( int i = 0; i < myLineNumber; ++i ) { line = reader.ReadLine(); } } } 
+12
Aug 11 '09 at 21:28
source share

No, unfortunately, no. At the source level, files do not work based on line number. Instead, they work in position / offset. The root file system has no concept of lines. This is a concept added by higher level components.

So, there is no way to tell the operating system, please open the file on the blah line. Instead, you need to open the file and skip counting new lines until you pass the specified number. Then save the next set of bytes into an array until you hit the next new line.

+4
Aug 11 '09 at 21:23
source share

If you do not have fixed line sizes, you need to read each line until you reach the desired line. Although you do not need to store each line, just discard it if it does not match your line.

Edit:

As already mentioned, one could search in a file if the length of the lines would be predictable, i.e. one could apply some deterministic function to convert the line number to the file position.

+3
Aug 11 '09 at 21:21
source share

As Mehrdad said, you cannot just search for the nth line without reading the file. However, you do not need to store the entire file in memory - just discard the data that you do not need.

 string line; using (StreamReader sr = new StreamReader(path)) for (int i = 0; i<15; i++) { line = sr.ReadLine(); if (line==null) break; // there are less than 15 lines in the file } 
+2
Aug 11 '09 at 21:28
source share

Read five lines each time, just insert your statement in the if statement, that's all

  String str1 = @"C:\Users\TEMP\Desktop\StaN.txt"; System.IO.StreamReader file = new System.IO.StreamReader(str1); line = file.ReadLine(); Int32 ctn=0; try { while ((line = file.ReadLine()) != null) { if (Counter == ctn) { MessageBox.Show("I am here"); ctn=ctn+5; continue; } else { Counter++; //MessageBox.Show(Counter.ToString()); MessageBox.Show(line.ToString()); } } file.Close(); } catch (Exception er) { } 
+2
Jul 12 '13 at 14:57
source share

If the lines have a fixed length, you can use the Seek method for the stream to go to the correct starting position.

If the strings are of variable length, your options are more limited.

If this is a file, you will use it once, and then discard it, then it is best for you to read it and work with it in memory.

If this is a file that you will be storing and reading more than writing, you can create your own index file containing the starting positions of each line. Then use this index to get the search position. The process of creating an index file is resource intensive. Every time you add a new line to a file, you need to update the index, so maintenance becomes a non-trivial problem.

+1
Aug 11 '09 at 21:28
source share

You can read line by line, so you don’t need to read everything at once (perhaps in general)

 int i=0 while(!stream.eof() && i!=lineNum) stream.readLine() i++ line = stream.readLine() 
0
Aug 11 '09 at 21:22
source share

If your file contains lines of different lengths, and you need to read lines often, and you need to read them quickly, you can index the file by reading it once, keeping the position of each new line, and then when you need to read the line, you simply look at the line position in your index, look there, and then read the line.

If you add new lines to the file, you can simply add an index of new lines, and you do not need to reindex everything. Although, if your file changes somewhere in the line that you already indexed, you need to reindex.

0
Sep 18 '09 at 22:09
source share

As long as you cannot search for the N'th line directly in the asymmetric file without reading the data in the file (because you need to count how many lines you went to the file), you can count line breaks until you get the line you need that takes up smallest memory and probably has better performance.

This will be more memory efficient than reading the whole array, since it will only read the file until it hits the end of the file or line number (whichever comes first). This is far from ideal, but is likely to satisfy your needs:

 string line15 = ReadLine(@"C:\File.csv", 15); public string ReadLine(string FilePath, int LineNumber){ string result = ""; try{ if( File.Exists(FilePath) ){ using (StreamReader _StreamReader = new StreamReader(FilePath)){ for (int a = 0; a < LineNumber; a++) { result = _StreamReader.ReadLine(); } } } }catch{} return result; } 
0
Oct 22 '12 at 4:16
source share

Tried and tested. It is so simple:

 string line = File.ReadLines(filePath).ElementAt(actualLineNumber - 1); 

As long as you have a text file, this should work. Later, depending on the data you expect to read, you can overlay the line accordingly and use it.

0
Nov 18 '17 at 22:06
source share

Variation Throws an error if the line number is greater than the number of lines.

 string GetLine(string fileName, int lineNum) { using (StreamReader sr = new StreamReader(fileName)) { string line; int count = 1; while ((line = sr.ReadLine()) != null) { if(count == lineNum) { return line; } count++; } } return "line number is bigger than number of lines"; } 
0
May 01 '18 at 17:09
source share
  if (File.Exists(fpath)) { var data = File.ReadLines(fpath); Console.WriteLine(data.ToArray()[14]); } 
-one
Apr 11 '15 at 11:34
source share

Late answer, but worth it.

You need to load the rows in an array or list object, where each row will be assigned an index, and then just call any range of rows by index in the loop.

The solution is pretty good, but between them there is memory consumption.

try it ... it's worth it

-2
Oct 17 '11 at 19:17
source share



All Articles