I'm using the try-catch block with two catch clauses. I want to load an XML file from a specific path and I'm checking if the directory exists in the first clause to create the directory, and in the second if the file exists to create the file. However, I know that if the directory doesn't exist, the file will not either.
So I am thinking if there is a way to not duplicate the code. I know I can create a boolean variable and then check if its true and create the file but I thought there might be a nice, clean solution that I just don't know how to search for.
XmlDocument document = new XmlDocument();
try
{
document.Load(folderPath + @"\XMLfile.xml"); // folderPath variable is assigned before depending on user input
}
catch(System.IO.DirectoryNotFoundException)
{
// if folder doesn't exist then the file will not either
System.IO.Directory.CreateDirectory(folderPath);
document.LoadXml("<?xml version=\"1.0\"?> \n" +
"<elements> \n" +
"</elements>");
}
catch (System.IO.FileNotFoundException)
{
// if folder exists then the file might as well, if not, creating the file's structure
document.LoadXml("<?xml version=\"1.0\"?> \n" +
"<elements> \n" +
"</elements>");
}
Ideally I would like to know if there is a way to avoid duplicating the code but still keep both exceptions. Is a boolean variable for example createFile in both catch clauses the only way to do in a somewhat nice way?