在使用XDocument.Load()加载文件之前,如何测试文件以查看它是否为有效的XML文件? [英] How does one test a file to see if it's a valid XML file before loading it with XDocument.Load()?
问题描述
我正在使用以下内容在C#应用程序中加载XML文档:
I'm loading an XML document in my C# application with the following:
XDocument xd1 = new XDocument();
xd1 = XDocument.Load(myfile);
但是在此之前,我会进行测试以确保文件存在:
but before that, I do test to make sure the file exists with:
File.Exists(myfile);
但是...是否有一种(简便)方法可以在XDocument.Load()之前测试文件,以确保它是有效的XML文件?换句话说,我的用户可能不小心在文件浏览器中单击了另一个文件,然后尝试加载,例如.php文件导致了异常.
But... is there an (easy) way to test the file before the XDocument.Load() to make sure it's a valid XML file? In other words, my user can accidentally click on a different file in the file browser and trying to load, say, a .php file causes an exception.
我唯一想到的方法是将其加载到StreamWriter中,并简单地对前几个字符进行文本搜索,以确保它们说出
谢谢!
The only way I can think of is to load it into a StreamWriter and simple do a text search on the first few characters to make sure they say "
Thanks!
-阿德娜(Adeena)
-Adeena
推荐答案
如果要向用户显示消息,可能值得捕获特定的异常:
It's probably just worth catching the specific exception if you want to show a message to the user:
try
{
XDocument xd1 = new XDocument();
xd1 = XDocument.Load(myfile);
}
catch (XmlException exception)
{
ShowMessage("Your XML was probably bad...");
}
这篇关于在使用XDocument.Load()加载文件之前,如何测试文件以查看它是否为有效的XML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!