Search code examples
c#loopsxmlreader

error when looping through xml files in directory with XmlTextReader


I am using the following code to loop through a directory, looking for xml files and readind them in:

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;
    }

}

When I use XML.Create on the single file (see BUT THIS WORKS), I can read everything in that document. When I use it with fi.Name, I get to see the message "Processing file: ", then, for every single xml file in the directory, I see "Could not find file 'C:\Documents and Settings\\My Documents\Visual Studio 2010\Projects\MoveReportsTest\MoveReportsTest\bin\Debug\.

I tried moving the reader instantiation around, at first, it was instantiated for every file, I tried moving the reader.Close() around, thinking I can't instantiate the same reader for every file, but it didn't change anything (same error). The 'could not find file message is not coming from any catch phrase... I am clueless... please help! Thanks!


Solution

  • As you refer to fi.Name it picks just the name of the file. If you in the path you provide only the name of the file, the default path will be the folder where you binaries are, so that one you see in exception : C:\Documents and Settings\\My Documents\Visual Studio 2010\Projects\MoveReportsTest\MoveReportsTest\bin\Debug\.

    Pass complete path to the XML file you gonna read => fi.FullName.