Click here to Skip to main content
11,439,025 members (77,866 online)
Click here to Skip to main content

Serializing to a File

, 30 Jul 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Helper for serializing objects in XML or binary and saving to a file

Introduction

I had previously published a tip (Serializing to a String[^]) on serializing objects to a string because I had a need to save to an object to Settings. Somebody commented that it would be more efficient to save a binary, which is true, but I do not think you can save binary to a Settings entry. This is a class that I would use if I had to save to a file. Can easily be changed to either XML or binary.

Potential Serializer Gotchas

There are a number of issues that you can run into when serializing, and the compiler does not seem to be much help and the error messages are not much either:

  • Properties of classes to be serialized must be public
  • All properties that are not marked to not be serialized must have both a setter and getter
  • The class to be serialized must have a default constructor which is a constructor that takes no parameters

The Code

The class that does the serialization and deserialization to an XML file is two short static methods in a static class:

    /// <summary />
    /// Serialize an object to an XML file.
    /// </summary />
    public static bool SerializedToXmlFile<t />(T serializableObject, string fileName)
    {
      if (serializableObject.Equals(default(T))) return false;
      try
      {
        var serializer = new XmlSerializer(typeof(T));
        using (var writer = new StreamWriter(fileName))
          serializer.Serialize(writer, serializableObject);
        return true;
      }
      catch (Exception ex)
      {
        return false;
      }
    }
 
    /// <summary />
    /// De-serialize an XML file into an object
    /// </summary />
    public static T DeSerializeFromXmlFile<t />(string fileName)
    {
      try
      {
        var serializer = new XmlSerializer(typeof(T));
        using (var reader = new StreamReader(fileName))
          return (T)serializer.Deserialize(reader);
      }
      catch (Exception ex)
      {
        return default(T);
      }
    }

The class that does the serialization and deserialization to an binary file is also two short static methods in a static class:

    /// <summary />
    /// Serialize an object to an Binary file.
    /// </summary />
    public static bool SerializedToBinaryFile<t />(T serializableObject, string fileName)
    {
      if (serializableObject.Equals(default(T))) return false;
      try
      {
        var serializer = new BinaryFormatter();
        using (var writer = File.Open(fileName, FileMode.Create))
          serializer.Serialize(writer, serializableObject);
        return true;
      }
      catch (Exception ex)
      {
        return false;
      }
    }
 
    /// <summary />
    /// De-serialize an Binary file into an object
    /// </summary />
    public static T DeSerializeFromBinaryFile<t />(string fileName)
    {
      try
      {
        var serializer = new BinaryFormatter();
        using (var reader = File.Open(fileName, FileMode.Open, FileAccess.Read))
          return (T)serializer.Deserialize(reader);
      }
      catch (Exception ex)
      {
        return default(T);
      }
    }

Saving an object to binary has two advantages compared to XML: smaller size, and very difficult for a user read. Of course saving in XML has the advantage of being able to look at the saved data and diagnose problems. Also, for real security, really need to encrypt the file to protect it.

There is really no error handling in these, and it may be desirable to put it in.

Summary

These methods makes it very easy to serialize an object to and from a file. It proves appropriate level of encapsulation when the file path is known, but probably is not appropriate if the user will be asked for the file

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Clifford Nelson
Software Developer (Senior) ETeam/Delloitte
United States United States
Has been working as a C# developer on contract for the last several years, including 3 years at Microsoft. Previously worked with Visual Basic and Microsoft Access VBA, and have developed code for Word, Excel and Outlook. Started working with WPF in 2007 when part of the Microsoft WPF team. For the last three years has been working primarily as a senior WPF/C# and Silverlight/C# developer. Currently working as WPF developer with NBC Universal in Universal City, CA

Comments and Discussions

 
QuestionGood Article Pin
Mike DiRenzo6-Nov-13 6:24
memberMike DiRenzo6-Nov-13 6:24 
AnswerRe: Good Article Pin
Clifford Nelson6-Nov-13 8:05
memberClifford Nelson6-Nov-13 8:05 
GeneralMy vote of 1 Pin
rmiguel16-Aug-13 0:56
memberrmiguel16-Aug-13 0:56 
AnswerRe: My vote of 1 Pin
Clifford Nelson16-Aug-13 1:26
memberClifford Nelson16-Aug-13 1:26 
GeneralRe: My vote of 1 Pin
rmiguel16-Aug-13 2:07
memberrmiguel16-Aug-13 2:07 
GeneralRe: My vote of 1 Pin
Rob Philpott16-Aug-13 23:28
professionalRob Philpott16-Aug-13 23:28 
GeneralRe: My vote of 1 Pin
rmiguel17-Aug-13 23:45
memberrmiguel17-Aug-13 23:45 
GeneralRe: My vote of 1 Pin
Rob Philpott18-Aug-13 1:28
professionalRob Philpott18-Aug-13 1:28 
GeneralRe: My vote of 1 Pin
rmiguel18-Aug-13 1:50
memberrmiguel18-Aug-13 1:50 
GeneralRe: My vote of 1 Pin
Andreas Gieriet8-Oct-13 23:30
memberAndreas Gieriet8-Oct-13 23:30 
GeneralCongratulation Pin
Socrates Lopes13-Aug-13 4:36
memberSocrates Lopes13-Aug-13 4:36 
GeneralMy vote of 3 Pin
Socrates Lopes13-Aug-13 4:34
memberSocrates Lopes13-Aug-13 4:34 
GeneralThanks Pin
db7uk12-Aug-13 21:48
professionaldb7uk12-Aug-13 21:48 
AnswerRe: Thanks Pin
Clifford Nelson13-Aug-13 6:05
memberClifford Nelson13-Aug-13 6:05 
GeneralVote of 5 Pin
Simon_Whale12-Aug-13 0:01
professionalSimon_Whale12-Aug-13 0:01 
AnswerRe: Vote of 5 Pin
Clifford Nelson12-Aug-13 7:30
memberClifford Nelson12-Aug-13 7:30 
GeneralMy vote of 4 Pin
Cindy Meister10-Aug-13 7:03
memberCindy Meister10-Aug-13 7:03 
GeneralMy vote of 2 Pin
Danielvrhyn8-Aug-13 3:31
memberDanielvrhyn8-Aug-13 3:31 
AnswerRe: My vote of 2 Pin
Clifford Nelson8-Aug-13 6:32
memberClifford Nelson8-Aug-13 6:32 
GeneralMy vote of 1 Pin
Member 88448601-Aug-13 2:57
memberMember 88448601-Aug-13 2:57 
AnswerRe: My vote of 1 Pin
Clifford Nelson3-Aug-13 13:51
memberClifford Nelson3-Aug-13 13:51 
SuggestionMake it a tip or trick Pin
Julian Goldsmith30-Jul-13 11:02
memberJulian Goldsmith30-Jul-13 11:02 
AnswerRe: Make it a tip or trick Pin
Clifford Nelson30-Jul-13 11:25
memberClifford Nelson30-Jul-13 11:25 
GeneralRe: Make it a tip or trick Pin
Julian Goldsmith1-Aug-13 4:26
memberJulian Goldsmith1-Aug-13 4:26 
AnswerRe: Make it a tip or trick [modified] Pin
Clifford Nelson1-Aug-13 7:57
memberClifford Nelson1-Aug-13 7:57 
GeneralMy vote of 3 Pin
DanielSheets30-Jul-13 8:52
memberDanielSheets30-Jul-13 8:52 
AnswerRe: My vote of 3 Pin
Clifford Nelson30-Jul-13 9:11
memberClifford Nelson30-Jul-13 9:11 
GeneralRe: My vote of 3 Pin
Adam Clauss30-Jul-13 15:36
memberAdam Clauss30-Jul-13 15:36 
AnswerRe: My vote of 3 Pin
Clifford Nelson30-Jul-13 16:09
memberClifford Nelson30-Jul-13 16:09 
GeneralRe: My vote of 3 Pin
Adam Clauss30-Jul-13 17:40
memberAdam Clauss30-Jul-13 17:40 
AnswerRe: My vote of 3 Pin
Clifford Nelson30-Jul-13 17:57
memberClifford Nelson30-Jul-13 17:57 
GeneralRe: My vote of 3 Pin
Adam Clauss30-Jul-13 18:09
memberAdam Clauss30-Jul-13 18:09 
AnswerRe: My vote of 3 Pin
Clifford Nelson30-Jul-13 18:30
memberClifford Nelson30-Jul-13 18:30 
GeneralRe: My vote of 3 Pin
Adam Clauss31-Jul-13 3:54
memberAdam Clauss31-Jul-13 3:54 
GeneralRe: My vote of 3 Pin
DanielSheets31-Jul-13 10:45
memberDanielSheets31-Jul-13 10:45 
AnswerRe: My vote of 3 Pin
Clifford Nelson31-Jul-13 15:14
memberClifford Nelson31-Jul-13 15:14 
GeneralRe: My vote of 3 Pin
DanielSheets1-Aug-13 2:23
memberDanielSheets1-Aug-13 2:23 
GeneralRe: My vote of 3 Pin
Paul891-Aug-13 4:52
memberPaul891-Aug-13 4:52 
GeneralRe: My vote of 3 Pin
DanielSheets1-Aug-13 5:16
memberDanielSheets1-Aug-13 5:16 
AnswerRe: My vote of 3 Pin
Clifford Nelson1-Aug-13 7:54
memberClifford Nelson1-Aug-13 7:54 
AnswerRe: My vote of 3 Pin
Clifford Nelson1-Aug-13 8:07
memberClifford Nelson1-Aug-13 8:07 
GeneralRe: My vote of 3 Pin
DanielSheets1-Aug-13 8:21
memberDanielSheets1-Aug-13 8:21 
AnswerRe: My vote of 3 Pin
Clifford Nelson30-Jul-13 18:50
memberClifford Nelson30-Jul-13 18:50 
GeneralRe: My vote of 3 Pin
Adam Clauss31-Jul-13 3:53
memberAdam Clauss31-Jul-13 3:53 
GeneralRe: My vote of 3 Pin
mad god31-Jul-13 13:31
membermad god31-Jul-13 13:31 
GeneralRe: My vote of 3 Pin
Paul8931-Jul-13 7:22
memberPaul8931-Jul-13 7:22 
QuestionAvoid calling writer.Close() Pin
Darek Danielewski30-Jul-13 5:36
memberDarek Danielewski30-Jul-13 5:36 
AnswerRe: Avoid calling writer.Close() Pin
Clifford Nelson30-Jul-13 6:22
memberClifford Nelson30-Jul-13 6:22 
GeneralMy vote of 5 Pin
Southmountain26-Jul-13 7:23
memberSouthmountain26-Jul-13 7:23 
GeneralRe: My vote of 5 Pin
Clifford Nelson26-Jul-13 7:36
memberClifford Nelson26-Jul-13 7:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150506.1 | Last Updated 30 Jul 2013
Article Copyright 2013 by Clifford Nelson
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid