Reputation: 15
i'm trying to read a file but i need to control the line number in the file. I try with StreamReader.ReadLine method but I can't control line number.
This is my code:
private void abrirToolStripMenuItem_Click(object sender, EventArgs e)
{
string line;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new
StreamReader(openFileDialog1.FileName);
//Read specified line with StreamReader
sr.Close();
}
}
Its a form, the design is in Spanish.
Please anyone can help me?
Upvotes: 1
Views: 6452
Reputation: 128
You can try with this method : Read file to array then you can control the line number in the file easily and efficiently.
string output = "";
string[] lines = File.ReadAllLines(String.Concat(@textBox1.Text, "\\temp\\test.txt"));
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains("Binh"))
{
output = lines[i - 1];
}
}
Upvotes: 0
Reputation: 38767
You can use File.ReadLines()
which returns an IEnumerable<string>
. You can then use LINQ's Skip()
and FirstOrDefault()
methods to go to skip the number of lines you want, and take the first item (or return null if there are no more items):
line = File.ReadLines().Skip(lineNumber - 1).FirstOrDefault()
Jeppe has commented that this can also be written like this:
line = File.ReadLines().ElementAtOrDefault(lineNumber - 1);
I use lineNumber - 1
because it is skipping lines, so you want to specify Skip(0)
for line 1.
As already mentioned, this will set line
to null
if the line isn't beyond the end of the file.
If you have to use StreamReader
, then all you can do is to call ReadLine()
in a loop until you reach the line number you want or the end of the file:
line = null;
for (int i = 0; i < lineNumber; ++i)
{
if ((line = sr.ReadLine()) == null)
{
break; // end of file reached
}
}
Upvotes: 5
Reputation: 1596
The StreamReader.ReadLine method allows you to read line by line, which will avoid loading the entire file into memory, which may be an issue for large files.
Readline will return null when it reaches the end of the file, so a while loop testing for that, with an internal counter will read line by line until the required line or EOF is found.
private void abrirToolStripMenuItem_Click(object sender, EventArgs e)
{
const int specifiedLine = 32;
string line;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
line = GetSpecifiedLine(openFileDialog1.FileName, specifiedLine);
}
}
private string GetSpecifiedLine(string fileName, int specifiedLine)
{
int lineCount = 0;
using (StreamReader sr = new StreamReader(fileName))
{
lineCount++;
var line = sr.ReadLine();
while (line != null)
{
if (lineCount == specifiedLine)
{
return line;
}
line = sr.ReadLine();
}
return null;
}
}
Upvotes: 0