在我的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()时,如何前进到下一行?
提前致谢.
您需要保持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)
| 归档时间: |
|
| 查看次数: |
4950 次 |
| 最近记录: |