读取文本文件中的所有行并添加它们C#

时间:2013-08-19 17:21:07

标签: c# .net for-loop while-loop

我一直在研究这个问题,我有点卡住了。我有一个文本文件,我需要循环并读取所有行,然后将所有子串一起添加到最后一个数字。问题是,我所拥有的是正确读取并仅生成文件中第一行的编号。我不确定是否使用'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);

我们非常感谢任何建议。

3 个答案:

答案 0 :(得分:4)

您使用while循环来执行此操作,读取每一行并检查它是否为hasn't returned 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
    }

答案 1 :(得分:1)

使用File.ReadLines

更容易
foreach(var line in File.ReadLines(filepath))
{
    //do stuff with line
}

答案 2 :(得分:1)

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

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

}