Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
var path = @"C:\Downloads\cesu";
            var result = @"C:\Downloads\Meternames.txt";
            File.WriteAllText(result, string.Empty);
            foreach (var file in System.IO.Directory.GetFiles(path, "*.xml"))
            {
                Console.WriteLine(file);
                XDocument xdoc = XDocument.Load(file);/* Here an exception is being thrown at some file :System.Xml.XmlException: 'The 'EVENT' start tag on line 29 position 484324 does not match the end tag of 'D5'. Line 29, position 529011.'*/

                
                string uid = xdoc.Descendants("G1").First()?.Value;
                Console.WriteLine(uid);
                using (StreamWriter sw = File.AppendText(result))
                {
                    sw.WriteLine(uid);
                }

            }
        }


What I have tried:

I want to skip that file and continue with reading of all files. Please suggest/modify the code so that I can skip the files with error and continue reading rest of the files.
I am reading approx 40000 files.
Posted
Updated 24-Jun-21 22:57pm

1 solution

Just add a try ... catch block:
C#
foreach (string file in System.IO.Directory.GetFiles(path, "*.xml"))
    {
    Console.WriteLine(file);
    try
        {
        XDocument xdoc = XDocument.Load(file);
        string uid = xdoc.Descendants("G1").First()?.Value;
        Console.WriteLine(uid);
        using (StreamWriter sw = File.AppendText(result))
            {
            sw.WriteLine(uid);
            }
        }    
    catch (Exception e)
        {
        Console.WriteLine($"Unable to load \"{file}\"\n   {e.Message}");
        }
    }
 
Share this answer
 
Comments
Himansh jain 25-Jun-21 5:26am    
thank you Sir :)
OriginalGriff 25-Jun-21 5:38am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900