【问题标题】:error when looping through xml files in directory with XmlTextReader使用 XmlTextReader 遍历目录中的 xml 文件时出错
【发布时间】:2012-04-17 22:53:51
【问题描述】:

我正在使用以下代码循环目录,查找 xml 文件并将它们读入:

XmlReader reader = null;

foreach (string file in files)
{
   try
   {
     System.IO.FileInfo fi = new System.IO.FileInfo(file);

     string fext = fi.Extension;
     if (fext == ".xml")
     {
         Console.WriteLine("Processing file:" + fi.Name);
         reader = XmlReader.Create(fi.Name);
       **//BUT THIS WORKS---> reader = new XmlReader(@"\\10.00.100.11   \Data\Cognos\ReportOutput\Test\Risk Rating Exception Detail (LN-133-D)-en-us_2012-04-14T031017814Z-pdf_desc.xml");**

          while (reader.Read())
          {
              switch (reader.NodeType)
              {
                 case XmlNodeType.Element: // The node is an element.
                      Console.Write("<" + reader.Name);
                      Console.WriteLine(">");
                      break;
                 case XmlNodeType.Text: //Display the text in each element.
                      Console.WriteLine(reader.Value);
                      break;
                 case XmlNodeType.EndElement: //Display the end of the element.
                      Console.Write("</" + reader.Name);
                      Console.WriteLine(">");
                      break;
              }

           }

           reader.Close();

       }

    }
    catch (System.IO.FileNotFoundException e)
    {
     // If file was deleted by a separate application or thread since the call to TraverseTree() then just continue.
         Console.WriteLine(e.Message);
         continue;
    }

}

当我在单个文件上使用 XML.Create 时(请参阅但是这可行),我可以读取该文档中的所有内容。当我将它与 fi.Name 一起使用时,我看到消息“处理文件:”,然后,对于目录中的每个 xml 文件,我看到“找不到文件 'C:\Documents and Settings\\My Documents \Visual Studio 2010\Projects\MoveReportsTest\MoveReportsTest\bin\Debug\。

我尝试移动阅读器实例化,起初,它是为每个文件实例化的,我尝试移动 reader.Close(),认为我不能为每个文件实例化相同的阅读器,但它没有改变任何东西(同样的错误)。 '找不到文件消息不是来自任何流行语......我一无所知......请帮助!谢谢!

【问题讨论】:

  • fi.Name 似乎很可疑。您可能需要 fi.FullName 代替。您还可以尝试添加“catch(Exception exception)”来捕获不仅仅是 FileNotFound。这可能有助于排除故障。

标签: c# loops xmlreader


【解决方案1】:

当您提到fi.Name 时,它只选择文件的名称。如果您在路径中仅提供文件名,默认 路径将是您的二进制文件所在的文件夹,因此您会在异常中看到一个:C:\Documents and Settings\\My Documents\Visual Studio 2010\Projects\MoveReportsTest\MoveReportsTest\bin\Debug\

完整路径传递到您要读取的XML 文件 => fi.FullName

【讨论】:

  • 这是问题所在,谢谢,但是,现在它的行为不正常,我什至在看到“处理文件:..”显示之前就看到了一堆标签,这使得没有感觉。我是否正确使用了 reader.Close()? (只是通过 xml 文件排除循环)?非常感谢!!
  • 再次感谢,好像是在读取 2 个文件后停止处理,我会调查一下。
【解决方案2】:

由于错误,听起来您正在搜索相对位置的文件,但请记住,如果您仅使用 fi.Name,它将寻找相对位置,如果您建议使用 fi.FullName没有使用相对位置。

FileInfo -> C:/Location/File.Ext
FileInfo.Name -> File.Ext
FileInfo.FullName -> C:/Location/File.Ext

reader = XmlReader.Create(fi.FullName);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 2010-12-16
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多