简体   繁体   English

文本文件:逐行读取#

[英]text file: Reading line by line C#

So, let's say i have a text file with 20 lines, with on each line different text. 所以,假设我有一个包含20行的文本文件,每行都有不同的文本。 i want to be able to have a string that has the first line in it, but when i do NextLine(); 我希望能够有一个包含第一行的字符串,但是当我做NextLine(); i want it to be the next line. 我希望它成为下一行。 I tried this but it doesn't seem to work: 我试过这个,但它似乎不起作用:

string CurrentLine; 
int LastLineNumber;   
Void NextLine() 
{
     System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
     CurrentLine = file.ReadLine(LastLineNumber + 1);
     LastLineNumber++;
}

How would i be able to do this? 我怎么能这样做? Thanks in advance. 提前致谢。

In general, it would be better if you could design this in a way to leave your file open, and not try to reopen the file each time. 一般情况下,如果您能够以打开文件的方式设计它,而不是每次都尝试重新打开文件,那会更好。

If that is not practical, you'll need to call ReadLine multiple times: 如果这不切实际,您需要多次调用ReadLine

string CurrentLine; 
int LastLineNumber;   
void NextLine() 
{
    // using will make sure the file is closed
    using(System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt"))
    {
        // Skip lines
        for (int i=0;i<LastLineNumber;++i)
            file.ReadLine();

        // Store your line
        CurrentLine = file.ReadLine();
        LastLineNumber++;
    }
}

Note that this can be simplified via File.ReadLines : 请注意,这可以通过File.ReadLines简化:

void NextLine() 
{
    var lines = File.ReadLines("C:\\test.txt");

    CurrentLine = lines.Skip(LastLineNumber).First();
    LastLineNumber++;
}

One simple call should do it: 一个简单的电话应该这样做:

var fileLines = System.IO.File.ReadAllLines(fileName);

You will want to validate the file exists and of course you still need to watch for blank lines or invalid values but that should give you the basics. 您需要验证文件是否存在,当然您仍需要查看空行或无效值,但这应该为您提供基础知识。 To loop over the file you can use the following: 要循环文件,您可以使用以下内容:

foreach (var singleLine in fileLines) {
   // process "singleLine" here
}

One more note - you won't want to do this with large files since it processes everything in memory. 还有一点需要注意 - 您不希望对大文件执行此操作,因为它会处理内存中的所有内容。

Well, if you really don't mind re-opening the file each time, you can use: 好吧,如果你真的不介意每次重新打开文件,你可以使用:

CurrentLine = File.ReadLines("c:\\test.txt").Skip(LastLineNumber).First();
LastLineNumber++;

However, I'd advise you to just read the whole thing in one go using File.ReadAllLines , or perhaps File.ReadLines(...).ToList() . 但是,我建议你使用File.ReadAllLines或者File.ReadLines(...).ToList()一次性阅读整个内容。

The ReadLine method already reads the next line in the StreamReader , you don't need the counter, or your custom function for that matter. ReadLine方法已经读取了StreamReader的下一行,您不需要计数器或自定义函数。 Just keep reading until you reach your 20 lines or until the file ends. 只需继续阅读,直到达到20行或文件结束。

You can't pass a line number to ReadLine and expect it to find that particular line. 您不能将行号传递给ReadLine并期望它找到该特定行。 If you look at the ReadLine documentation , you'll see it doesn't accept any parameters. 如果您查看ReadLine文档 ,您将看到它不接受任何参数。

public override string ReadLine()

When working with files, you must treat them as streams of data. 处理文件时,必须将它们视为数据流 Every time you open the file, you start at the very first byte/character of the file. 每次打开文件时,都从文件的第一个字节/字符开始。

var reader = new StreamReader("c:\\test.txt");      // Starts at byte/character 0

You have to keep the stream open if you want to read more lines. 如果要读取更多行,则必须保持流打开。

using (var reader = new StreamReader("c:\\test.txt"))
{
    string line1 = reader.ReadLine();
    string line2 = reader.ReadLine();
    string line3 = reader.ReadLine();
    // etc..
}

If you really want to write a method NextLine , then you need to store the created StreamReader object somewhere and use that every time. 如果你真的想编写一个方法NextLine ,那么你需要将创建的StreamReader对象存储在某个地方并且每次都使用它。 Somewhat like this: 有点像这样:

public class MyClass : IDisposable
{
    StreamReader reader;

    public MyClass(string path)
    {
        this.reader = new StreamReader(path);
    }

    public string NextLine()
    {
        return this.reader.ReadLine();
    }

    public void Dispose()
    {
        reader.Dispose();
    }
}

But I suggest you either loop through the stream: 但我建议你循环流:

using (var reader = new StreamReader("c:\\test.txt"))
{
    while (some_condition)
    {
        string line = reader.ReadLine();
        // Do something
    }
}

Or get all the lines at once using the File class ReadAllLines method : 或者使用FileReadAllLines方法一次获取所有行:

string[] lines = System.IO.File.ReadAllLines("c:\\test.txt");
for (int i = 0; i < lines.Length; i++)
{
    string line = lines[i];
    // Do something
}

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

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