【问题标题】:Read All Lines in a Text File and Add Them C#读取文本文件中的所有行并添加它们 C#
【发布时间】:2013-08-21 14:04:13
【问题描述】:

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

任何建议将不胜感激。

【问题讨论】:

  • 而 (reader.ReadLine()) { }
  • string[] words = System.IO.File.ReadAllLines(FilePath);

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


【解决方案1】:

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

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

}

【讨论】:

  • 当您可以使用ReadLines 流式传输它时,为什么要浪费整个文件中的所有内存读取。除此之外,您还可以避免拆分文本,从而提高性能,并确保该操作即使在具有\n 以外的新行的操作系统上也能正常工作。
  • 谢谢,这真的很有帮助。
【解决方案2】:

使用File.ReadLines 更容易:

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

【讨论】:

    【解决方案3】:

    您使用 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
        }
    

    【讨论】:

    • 我相信 OP 正在寻找所有行的总和,在这种情况下 int currentReturn += Convert.ToInt32... 可以解决问题。
    • Kyle,我正在寻找所有行的总和。我在上面 David N 的回答中运行了代码,虽然代码似乎在运行,但我的日志文件在第 26 行返回输入字符串的格式不正确,即“int soldToDate”行...
    • 我仍然在 int soldToDate 行收到“输入格式不正确”错误。我的每一行格式,例如 - (我子)0000010004000000000000.00000000000000.00000000000000.00 0000010010000000037462.25000000021645.00000000005228.00 0000010015000000027240.00000000017072.00000000002259.00如果我想忽略前10个字符,并读取下一个15出于某种原因,它不断示数出来。我尝试将子字符串更改为 10,12 以删除小数点和尾随零,但得到了相同的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    相关资源
    最近更新 更多