【发布时间】:2019-09-09 08:00:17
【问题描述】:
我正在使用带有两个 catch 子句的 try-catch 块。我想从特定路径加载 XML 文件,并检查目录是否存在于第一个子句中以创建目录,并在第二个子句中检查文件是否存在以创建文件。但是,我知道如果目录不存在,文件也不存在。
所以我在想是否有办法不复制代码。我知道我可以创建一个布尔变量,然后检查它是否为真并创建文件,但我认为可能有一个不错的、干净的解决方案,我只是不知道如何搜索。
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>");
}
理想情况下,我想知道是否有办法避免重复代码但仍保留两个异常。两个 catch 子句中的布尔变量(例如 createFile)是否是以某种不错的方式进行的唯一方法?
【问题讨论】:
-
写一个单独的方法来调用?如果你愿意,它可以是一个本地函数。