将C#ReadLine()前进到函数调用中的下一行

Sam*_*sey 2 c# readline

在我的C#应用​​程序中,我正在尝试将一个简单的文本文档输入ReadLine(),其中7位数字符串逐行分隔.我试图做的是每次调用函数时抓取下一个7位数字符串.这是我到目前为止所拥有的:

string invoiceNumberFunc()
    {
        string path = @"C:\Users\sam\Documents\GCProg\testReadFile.txt";
        try
        {
            using (StreamReader sr = new StreamReader(path))
            {
                invoiceNumber = sr.ReadLine();

            }

        }
        catch (Exception exp)
        {
            Console.WriteLine("The process failed: {0}", exp.ToString());
        }
       return invoiceNumber;
    }
Run Code Online (Sandbox Code Playgroud)

每次调用invoiceNumberFunc()时,如何前进到下一行?

提前致谢.

Jon*_*eet 8

您需要保持StreamReader中间调用,或者将其作为新参数传递给方法,或者将其作为类的成员变量.

我个人更喜欢它成为一个参数的想法,所以它永远不会成为一个成员变量 - 这使得生命周期更容易管理:

void DoStuff()
{
    string path = @"C:\Users\sam\Documents\GCProg\testReadFile.txt";
    using (StreamReader sr = new StreamReader(path))
    {
        while (keepGoing) // Whatever logic you have
        {
            string invoice = InvoiceNumberFunc(sr);
            // Use invoice
        }
    }
}

string InvoiceNumberFunc(TextReader reader)
{
    string invoiceNumber;
    try
    {
        invoiceNumber = reader.ReadLine();
    }
    catch (Exception exp)
    {
        Console.WriteLine("The process failed: {0}", exp.ToString());
    }
    return invoiceNumber;
}
Run Code Online (Sandbox Code Playgroud)