检查 .xaml 文件是否有效
Check if a .xaml file is valid or not
我正在用 WPF 中的资源字典制作一个翻译系统。
但是我有一个问题,当我尝试在资源字典中加载一个无效的 xaml 文件时(像这样):
// Path is the path of my .xaml file (the file is invalid for the tests)
try {
Current = new ResourceDictionary() {
Source = new Uri(path)
};
} catch (Exception e) {
MessageBox.Show(e.Message);
}
它抛出异常。如果只是我能抓住它,我就知道xaml文件是否有效。
但问题是:try catch 没有得到异常。异常仍然使我的应用程序崩溃,我不知道为什么。
我真的很想知道文件是否有效。 (如果用户只是将路径设置为无效 xaml 文件,以防止应用程序崩溃)
那么有人知道如何捕获异常,或者在加载 xaml 文件之前知道它是否有效吗?
编辑:例外情况是:System.Windows.Markup.XamlParseException
我找到了解决方案:
// Check if file content is valid
try {
XElement.Load(path);
// The file is valid
}
catch {
// The file is not valid
return false;
}
我正在用 WPF 中的资源字典制作一个翻译系统。 但是我有一个问题,当我尝试在资源字典中加载一个无效的 xaml 文件时(像这样):
// Path is the path of my .xaml file (the file is invalid for the tests)
try {
Current = new ResourceDictionary() {
Source = new Uri(path)
};
} catch (Exception e) {
MessageBox.Show(e.Message);
}
它抛出异常。如果只是我能抓住它,我就知道xaml文件是否有效。
但问题是:try catch 没有得到异常。异常仍然使我的应用程序崩溃,我不知道为什么。
我真的很想知道文件是否有效。 (如果用户只是将路径设置为无效 xaml 文件,以防止应用程序崩溃)
那么有人知道如何捕获异常,或者在加载 xaml 文件之前知道它是否有效吗?
编辑:例外情况是:System.Windows.Markup.XamlParseException
我找到了解决方案:
// Check if file content is valid
try {
XElement.Load(path);
// The file is valid
}
catch {
// The file is not valid
return false;
}