Monday, August 26, 2013

System.IO.FileInfo cannot be serialized because it does not have a parameterless constructor.


Today I was working on Web Service in C#, my task was to get total number of files from specific directory their name, extension and than return this information to calling program.
This is the code I wrote for the above purpose


   1:  [WebMethod]
   2:          public FileInfo[] getDirectory(string dir)
   3:          {
   4:              DirectoryInfo objDI = new DirectoryInfo(dir);
   5:              FileInfo[] files= objDI.GetFiles();
   6:              return files;
   7:          }

 

But On execution I had the following error

Basically this error is straight forward the purpose of XML serialization is to encode the data so that it can be send over the internet, and at the receiving end can be decoded easily.



Now to re-create the data, the receiving end would call the default constructor, since no default constructor(parameter less) is defined, the data cannot be re-created, so the compiler is warning that serialization is not possible

To fix this error I created a custom class, assign data to the class than add the class in list, Finally return the list.





   1:  [WebMethod]
   2:   
   3:          public List<myClass> getDirectory()
   4:          {
   5:              List<myClass> objlist = new List<myClass>();
   6:              DirectoryInfo objDI = new DirectoryInfo(@"d:\magicdisc");
   7:              FileInfo[] files = objDI.GetFiles();
   8:              myClass c;
   9:              foreach (FileInfo f in files)
  10:              {
  11:                  c = new myClass();
  12:                  c.Name1 = f.Name;
  13:                  c.Extension = f.Extension;
  14:                  objlist.Add(c);
  15:              }
  16:              return objlist;
  17:          }

This way you can return all those classes which can't be serialized.

If you have further queries than do comment.

Thanks

No comments:

Post a Comment