Problems Working with XMLSerializer

You just saw one way to pass back data, but you might say that it involves a bit of work; there must be a simpler way to do it. Why not use the XMLSerializer class to generate the returning data in an XML valid format? Well, if you try this, you might get the following error message:

System.Exception: There was an error reflecting 'System.IO.DirectoryInfo'. –-> 
System.Exception: System.IO.DirectoryInfo cannot be serialized because it does not have a
 default public constructor. 
   at System.Xml.Serialization. TypeScope.ImportTypeDesc(Type type, Boolean canBePrimitive) 
   at System.Xml.Serialization. TypeScope.GetTypeDesc(Type type) 
   at System.Xml.Serialization.ModelScope.GetTypeModel(Type type) 
   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type,
 XmlRootAttribute root, String defaultNamespace) 
   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type,
 XmlRootAttribute root, String defaultNamespace) 
   at System.Xml.Serialization.XmlSerializer..ctor(Type type) 
   at chapter13_c.Service1.Dir(String dir) in c:documents and settingsradvswebcache
digital-laptopchapter13_cservice1.asmx.cs:line 110 

Let’s look at the line of code where the error occurred and see why this is happening. Listings 13.9 and 13.10 provide a fix.

Listing 13.9. Fix for the XMLSerializer problem (C#)
[WebMethod] 
   public Object[] Dir(string dir) 
   {
   XmlSerializer serializer =       new XmlSerializer(typeof(DirectoryInfo)); 
   Return serializer; 
   } 

Listing 13.10. Fix for the XMLSerializer problem (Visual Basic .NET)
<WebMethod()> Public Function Dir(ByVal dirname As String) As Object() 

      Dim serializer = new XmlSerializer(typeof(DirectoryInfo)) 
      Return serializer 

    End Function 

The XmlSerializer cannot serialize the structure into XML. That is why you must define the different classes to mimic the DirectoryInfo object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset