I need a snippet to check file for validity (I'm allowing users to upload xml files). So I need to check whether uploaded file is XML. The best I can think of is just check if extension is ".xml". What if its replaced?
我需要一个片段来检查文件的有效性(我允许用户上传xml文件)。所以我需要检查上传的文件是否是XML。我能想到的最好的只是检查扩展名是否为“.xml”。如果它被取代怎么办?
4 个解决方案
#1
3
You can try loading it like this and catch the exception:
您可以尝试像这样加载它并捕获异常:
XDocument xdoc = XDocument.Load("data.xml"));
#2
2
Presumably, if they're uploading XML, then you're going to use it for something afterwards. In this case you should validate the XML against a Schema (XSD etc) so that you know you aren't going to hit unexpected values/layouts etc.
据推测,如果他们正在上传XML,那么你将在之后使用它。在这种情况下,您应该根据Schema(XSD等)验证XML,以便您知道您不会遇到意外的值/布局等。
#3
0
In Urlmon.dll, there's a function called FindMimeFromData.
在Urlmon.dll中,有一个名为FindMimeFromData的函数。
From the documentation
从文档中
MIME type detection, or "data sniffing," refers to the process of determining an appropriate MIME type from binary data. The final result depends on a combination of server-supplied MIME type headers, file extension, and/or the data itself. Usually, only the first 256 bytes of data are significant.
MIME类型检测或“数据嗅探”是指从二进制数据中确定适当的MIME类型的过程。最终结果取决于服务器提供的MIME类型标头,文件扩展名和/或数据本身的组合。通常,只有前256个字节的数据才有意义。
So, read the first (up to) 256 bytes from the file and pass it to FindMimeFromData.
因此,从文件中读取第一个(最多)256个字节并将其传递给FindMimeFromData。
#4
0
If you must validate the xml (assuming you want to validate the entire thing) you can use the XmlDocument
class and catch an exception if it's not XML.
如果必须验证xml(假设您要验证整个事物),可以使用XmlDocument类并捕获异常(如果它不是XML)。
#1
3
You can try loading it like this and catch the exception:
您可以尝试像这样加载它并捕获异常:
XDocument xdoc = XDocument.Load("data.xml"));
#2
2
Presumably, if they're uploading XML, then you're going to use it for something afterwards. In this case you should validate the XML against a Schema (XSD etc) so that you know you aren't going to hit unexpected values/layouts etc.
据推测,如果他们正在上传XML,那么你将在之后使用它。在这种情况下,您应该根据Schema(XSD等)验证XML,以便您知道您不会遇到意外的值/布局等。
#3
0
In Urlmon.dll, there's a function called FindMimeFromData.
在Urlmon.dll中,有一个名为FindMimeFromData的函数。
From the documentation
从文档中
MIME type detection, or "data sniffing," refers to the process of determining an appropriate MIME type from binary data. The final result depends on a combination of server-supplied MIME type headers, file extension, and/or the data itself. Usually, only the first 256 bytes of data are significant.
MIME类型检测或“数据嗅探”是指从二进制数据中确定适当的MIME类型的过程。最终结果取决于服务器提供的MIME类型标头,文件扩展名和/或数据本身的组合。通常,只有前256个字节的数据才有意义。
So, read the first (up to) 256 bytes from the file and pass it to FindMimeFromData.
因此,从文件中读取第一个(最多)256个字节并将其传递给FindMimeFromData。
#4
0
If you must validate the xml (assuming you want to validate the entire thing) you can use the XmlDocument
class and catch an exception if it's not XML.
如果必须验证xml(假设您要验证整个事物),可以使用XmlDocument类并捕获异常(如果它不是XML)。