简体   繁体   English

如何在C#中读取文件的特定行

[英]How to read a specific line of a file in C#

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. 我尝试使用StreamReader.ReadLine方法,但无法控制行号。

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? 请任何人可以帮助我吗?

You can use File.ReadLines() which returns an IEnumerable<string> . 您可以使用File.ReadLines()返回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): 然后,您可以使用LINQ的Skip()FirstOrDefault()方法跳过所需的行数,并获取第一个项目(如果没有更多项目,则返回null):

line = File.ReadLines().Skip(lineNumber - 1).FirstOrDefault()

Jeppe has commented that this can also be written like this: 杰普(Jeppe)评论说,这也可以这样写:

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. 我使用lineNumber - 1因为它正在跳过行,因此您要为第1行指定Skip(0)

As already mentioned, this will set line to null if the line isn't beyond the end of the file. 如前所述,这将设置linenull如果该行不超出文件的末尾。


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: 如果必须使用 StreamReader ,那么您可以做的就是循环调用ReadLine() ,直到找到所需的行号或文件的结尾:

line = null;
for (int i = 0; i < lineNumber; ++i)
{
    if ((line = sr.ReadLine()) == null)
    {
        break; // end of file reached
    }
}

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. StreamReader.ReadLine方法允许您逐行读取,这将避免将整个文件加载到内存中,这对于大文件来说可能是个问题。

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. Readline到达文件末尾时将返回null,因此使用内部计数器进行while循环测试时,它会逐行读取直到找到所需的行或EOF。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM