How does one test a file to see if it's a valid XML file before loading it with XDocument.Load()?

后端 未结 7 1939
挽巷
挽巷 2020-12-28 14:24

I\'m loading an XML document in my C# application with the following:

XDocument xd1 = new XDocument();
xd1 = XDocument.Load(myfile);

but be

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-28 14:48

    I would not XDocument.Load(), as per the accepted answer; why would you read the entire file into memory, it could be a huge file?

    I'd probably read the first few bytes into a byteArray (it could even be any binary file), convert the byteArray to string e.g. System.Text.Encoding.ASCII.GetString(byteArray) ,check if the converted string contains the Xml elements you are expecting, only then continue.

提交回复
热议问题