visual studio 2010 - C# check if XML file is not corrupted before deserialization -


i didn't find problem in internet. deserialize data playlists.

he code :

using (var fs = new filestream("playlist.xml", filemode.openorcreate)) {  xmlserializer xml = new xmlserializer(typeof(observablecollection<playlist>));  if (fs.length > 0)   pl = (observablecollection<playlist>)xml.deserialize(fs);  else   pl = new observablecollection<playlist>(); } 

here result xml :

    <?xml version="1.0"?>     <arrayofplaylist xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"    xmlns:xsd="http://www.w3.org/2001/xmlschema">        <playlist>         <name>playlist1</name>           <list>              <media>                 <path>c:\users\tchiko\videos\suit tie (official lyric video).mp4</path>                 <name>suit tie (official lyric video).mp4</name>                 <type>video</type>              </media>          </list>      </playlist>      <playlist>         <name>hip hop</name>           <list>             <media>               <path>c:\users\tchiko\videos\suit tie (official lyric video).mp4</path>               <name>suit tie (official lyric video).mp4</name>               <type>video</type>             </media>          </list>       </playlist> </arrayofplaylist> 

before loading playlist, want check if user corrupted file hand. need check if format xml well, in order avoid conflicts after deserialization.

edit : version avoid error not-well format :

        using (var fs = new filestream("playlist.xml", filemode.openorcreate))         {             try             {                 xmlserializer xml = new xmlserializer(typeof(observablecollection<playlist>));                 if (fs.length > 0)                     pl = (observablecollection<playlist>)xml.deserialize(fs);                 else                     pl = new observablecollection<playlist>();             }             catch (exception ex)             {                   pl = new observablecollection<playlist>();             }         } 

thanks helps

to ensure xml validity you'll need define xml schema. xml schema declares tags, in order , type of values allowed in xml.

here article how validate xml against schema.

if xml not well-formed (as in, user didn't close tag or of sort), deserialization fail , you'll invalidoperationexception more details in innerexception. see xmlserializer.deserialize() on msdn.


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -