C# 在循环变量中维护数据

C# 在循环变量中维护数据,c#,C#,我的代码存在的问题是,它打开文件夹中的一个文件并读取第一行,如果它是标题(HDR),则它将该行分配给currentHDR变量,然后它将搜索文件中的错误,如果有错误,它将处理已知的两个常见错误,然后将currentHDR行和该行写入报告文件,然后将currentHDR分配给当前变量。这是为了确保在下一步检查同一文件时,不会写入标题行而写入任何进一步的错误。当它完成并打开新文件时,应该还有一些东西被分配给“current”,这就是为什么它会检查current是否为null,如果是,它会使curren

我的代码存在的问题是,它打开文件夹中的一个文件并读取第一行,如果它是标题(HDR),则它将该行分配给currentHDR变量,然后它将搜索文件中的错误,如果有错误,它将处理已知的两个常见错误,然后将currentHDR行和该行写入报告文件,然后将currentHDR分配给当前变量。这是为了确保在下一步检查同一文件时,不会写入标题行而写入任何进一步的错误。当它完成并打开新文件时,应该还有一些东西被分配给“current”,这就是为什么它会检查current是否为null,如果是,它会使current为null。然后继续循环

代码如下:

private string folderPath;
private object file;
public string current { get; private set; }
public string currentHDR { get; private set; }

public void Main()
{
  folderPath = "C:\\data\\";

  foreach (string pathToFile in Directory.EnumerateFiles(folderPath, "*.BER"))
  {
    using (System.IO.StreamWriter file =
         new System.IO.StreamWriter(@"c:\data\newreport.txt", true))
    {
      foreach (var line in File.ReadLines(pathToFile))
      {
        if (line.Contains("HDR") && current == null)
        {
          string currentHDR = line;
        }
        else if (line.Contains("HDR") && current != null)
        {
          string currentHDR = line;
          current = "";
        }

        if (line.Contains("ERR~") && line.Contains("Warnings exist"))
        { }
        else
        {
          if (line.Contains("ERR~") && line.Contains("DEPARTPORT"))
          { }
          else
          {
            if (line.Contains("ERR~WARNING") && current == null)
            {
              file.WriteLine(currentHDR);
              file.WriteLine(line);
              current = currentHDR;
            }
            else if (line.Contains("ERR~WARNING") && current != null)
            {
              file.WriteLine(line);
            }
          }
        }
      }
    }
  } 
}
目前的结果文件如下所示:

ERR~WARNING-SHP.TPTCTRY()对于SHP.TPTID(xxx)不能为空

ERR~WARNING-SHP.TPTCTRY()对于SHP.TPTID(xxx)不能为空

这清楚地表明currentHDR在尝试将该行写入文件时为空。就我所见,当它通过循环时,它似乎没有继续保持变量中的值


我是否误解了这是如何失败的?

问题在于以下几行:

if (line.Contains("HDR") && current == null)
{
   string currentHDR = line;
}
else if (line.Contains("HDR") && current != null)
{
   string currentHDR = line;
   current = "";
}
请注意,您使用的是
string currentHDR=…
,这意味着您要为每个
if
块声明一个不同的
currentHDR
变量。删除
字符串
类型声明,然后将使用预期的
currentHDR
字段:

if (line.Contains("HDR") && current == null)
{
   currentHDR = line;
}
else if (line.Contains("HDR") && current != null)
{
   currentHDR = line;
   current = "";
}

你能花点时间修改一下代码格式吗?@Amy现在好多了?你想要的行为是什么?请提供一个.Side注释:文件不应声明为“对象”。这是一个StreamWriter。把问题作为一个问题,不需要把答案中的“结果”放进去。绝对精彩!解释有道理,解决了我的问题……谢谢!