0

我一直在研究这个问题一段时间,我有点卡住了。我有一个文本文件,我需要遍历并读取所有行,然后将所有子字符串加在一起以获得一个最终数字。问题是,我所拥有的是正确读取并仅生成文件第一行的数字。我不确定是使用“while”还是“for each”。这是我的代码:

    string filePath = ConfigurationSettings.AppSettings["benefitsFile"];
    StreamReader reader = null;
    FileStream fs = null;
    try
    {
        //Read file and get estimated return.
        fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        reader = new StreamReader(fs);
        string line = reader.ReadLine();
        int soldToDate = Convert.ToInt32(Convert.ToDouble(line.Substring(10, 15)));
        int currentReturn = Convert.ToInt32(soldToDate * .225);

        //Update the return amount
        updateCurrentReturn(currentReturn);

任何建议将不胜感激。

4

3 回答 3

4

您使用 while 循环来执行此操作,读取每一行并检查它是否没有返回 null

    string filePath = ConfigurationSettings.AppSettings["benefitsFile"];
    StreamReader reader = null;
    FileStream fs = null;
    try
    {
        //Read file and get estimated return.
        fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        reader = new StreamReader(fs);

        string line;
        int currentReturn = 0;
        while ((line = reader.ReadLine()) != null){
            int soldToDate = Convert.ToInt32(Convert.ToDouble(line.Substring(10, 15)));
            currentReturn += Convert.ToInt32(soldToDate * .225);
        }

        //Update the return amount
        updateCurrentReturn(currentReturn);

    }
    catch (IOException e){
     // handle exception and/or rethrow
    }
于 2013-08-19T17:24:41.620 回答
1

使用起来更容易File.ReadLines

foreach(var line in File.ReadLines(filepath))
{
    //do stuff with line
}
于 2013-08-19T17:32:26.180 回答
1

这更加普遍,因为它适用于大多数文本。

string text = File.ReadAllText("file directory");
foreach(string line in text.Split('\n'))
{

}
于 2013-08-19T18:40:04.613 回答