日志文件输出与调试器不匹配

时间:2012-02-15 15:13:32

标签: c#

MS Visual Studio 2010中的C#。我将输出写入日志文件,作为一些代码验证的一部分。调试器显示组正在匹配,Match输出也是如此。唯一错误的是输出文件,我不知道为什么。这是我从文件中获得的输出,其中readline是输入行,Match是Regex匹配的结果,Slot / Port是从Regex中的命名组获取值的结果。您可以从日志中看到正则表达式匹配输入行。调试器说命名组正在工作。

readline is: fc1/1 is up
Match is: fc1/1 is
Slot and Port are: 1/1
readline is: fc1/3 is up
Match is: fc1/3 is
Slot and Port are: 1/1

以下是执行匹配的代码 - 我添加了一些额外的内容,以便在调试器中更容易观看。

if (RegexExtensions.TryMatch(out InterfaceMatch, trimmed, InterfaceMatchString))
                {
                    SlotNum = Convert.ToInt32(InterfaceMatch.Groups["slot"].Value);
                    PortNum = Convert.ToInt32(InterfaceMatch.Groups["port"].Value);
                    string slot = InterfaceMatch.Groups["slot"].Value;
                    string port = InterfaceMatch.Groups["port"].Value;
  // write the value of current incoming readline
                  CiscoDecodeVariables.swlog.WriteLine(String.Format("readline is: {0}", readline));
 // write the value of the current match
                  CiscoDecodeVariables.swlog.WriteLine(String.Format("Match is: {0}", InterfaceMatch.Value.ToString()));
                  string slotasstring = SlotNum.ToString();
                  string portasstring = PortNum.ToString();
   // here is the line that writes what the slot and port values are
               CiscoDecodeVariables.swlog.WriteLine(String.Format("Slot and Port are: {0}/{0}", slotasstring, portasstring));
                CiscoDecodeVariables.swlog.Flush();
                    //sw.Close();
                    currPort = ((PortModule)ModuleList[SlotNum]).FCPortList[PortNum - 1];
                }

最后,这是StreamWriter的代码。我用一个静态变量删除了一个静态类,所以我可以使用我需要的Streamwriter。

static public class CiscoDecodeVariables
{
    static public string LogFileOutPutPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\\ciscodecodelog.txt";
    static public StreamWriter swlog = new StreamWriter(LogFileOutPutPath);

}

添加有问题的RegEx匹配模式     string InterfaceMatchString = @“fc(?\ d +)/(?\ d +)是”;

此外,RegexExtensions.TryMatch()是一个静态方法,它为成功匹配返回true,并将InterfaceMatch实例设置为结果。

2 个答案:

答案 0 :(得分:2)

您的代码:

"Slot and Port are: {0}/{0}"

正确的代码:

"Slot and Port are: {0}/{1}"

简单的拼写错误看起来像。 :)

并澄清那些可能不理解第一行的人明确地将相同的东西放在两次(第一个后续参数),而第二行是放入第一个参数然后是第二个(通过{0 }和{1})。

作为附加说明String.Format接受任何对象,并且如果需要将在其上调用ToString,因此不需要首先转换为字符串(虽然我知道您可能已将这些行纯粹用于调试帮助)。还有一个InterfaceMatch.Value.ToString(),我相信Value应该已经是一个字符串了。

答案 1 :(得分:1)

这是您的格式字符串的问题。

CiscoDecodeVariables.swlog.WriteLine(String.Format("Slot and Port are: {0}/{0}", slotasstring, portasstring)); 

“{0} / {0}”表示您将获得结果“slotasstring / slotasstring”而不是“slotasstring / portasstring”。