Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#
Tip/Trick

Serializing to a File

Rate me:
Please Sign up or sign in to vote.
4.59/5 (35 votes)
30 Jul 2013CPOL2 min read 78.9K   633   50   55
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:

C#
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);
   writer.Close();
  }
  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 a binary file is also two short static methods in a static class:

C#
/// <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);
   writer.Close();
  }
  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)


Written By
Software Developer (Senior) Clifford Nelson Consulting
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 eight years has been working primarily as a senior WPF/C# and Silverlight/C# developer. Currently working as WPF developer with BioNano Genomics in San Diego, CA redesigning their UI for their camera system. he can be reached at qck1@hotmail.com.

Comments and Discussions

 
QuestionGood Article Pin
Mike DiRenzo6-Nov-13 5:24
Mike DiRenzo6-Nov-13 5:24 
AnswerRe: Good Article Pin
Clifford Nelson6-Nov-13 7:05
Clifford Nelson6-Nov-13 7:05 
GeneralMy vote of 1 Pin
Yet Another XCoder15-Aug-13 23:56
Yet Another XCoder15-Aug-13 23:56 
AnswerRe: My vote of 1 Pin
Clifford Nelson16-Aug-13 0:26
Clifford Nelson16-Aug-13 0:26 
GeneralRe: My vote of 1 Pin
Yet Another XCoder16-Aug-13 1:07
Yet Another XCoder16-Aug-13 1:07 
GeneralRe: My vote of 1 Pin
Rob Philpott16-Aug-13 22:28
Rob Philpott16-Aug-13 22:28 
GeneralRe: My vote of 1 Pin
Yet Another XCoder17-Aug-13 22:45
Yet Another XCoder17-Aug-13 22:45 
GeneralRe: My vote of 1 Pin
Rob Philpott18-Aug-13 0:28
Rob Philpott18-Aug-13 0:28 
GeneralRe: My vote of 1 Pin
Yet Another XCoder18-Aug-13 0:50
Yet Another XCoder18-Aug-13 0:50 
GeneralRe: My vote of 1 Pin
Andreas Gieriet8-Oct-13 22:30
professionalAndreas Gieriet8-Oct-13 22:30 
GeneralCongratulation Pin
Socrates Lopes13-Aug-13 3:36
professionalSocrates Lopes13-Aug-13 3:36 
GeneralMy vote of 3 Pin
Socrates Lopes13-Aug-13 3:34
professionalSocrates Lopes13-Aug-13 3:34 
GeneralThanks Pin
db7uk12-Aug-13 20:48
db7uk12-Aug-13 20:48 
AnswerRe: Thanks Pin
Clifford Nelson13-Aug-13 5:05
Clifford Nelson13-Aug-13 5:05 
GeneralVote of 5 Pin
Simon_Whale11-Aug-13 23:01
Simon_Whale11-Aug-13 23:01 
AnswerRe: Vote of 5 Pin
Clifford Nelson12-Aug-13 6:30
Clifford Nelson12-Aug-13 6:30 
PraiseRe: Vote of 5 Pin
Clifford Nelson17-Aug-16 5:12
Clifford Nelson17-Aug-16 5:12 
GeneralMy vote of 4 Pin
Cindy Meister10-Aug-13 6:03
Cindy Meister10-Aug-13 6:03 
This is a useful bit of code, but as someone with little experience in this area, I would appreciate more explanation, whether as comments in the code or text in the article. (Yes, I read you didn't intend an article!) For example, I don't understand the intent of if (serializableObject.Equals(default(T))) return false;
GeneralMy vote of 2 Pin
Danielvrhyn8-Aug-13 2:31
Danielvrhyn8-Aug-13 2:31 
AnswerRe: My vote of 2 Pin
Clifford Nelson8-Aug-13 5:32
Clifford Nelson8-Aug-13 5:32 
GeneralMy vote of 1 Pin
Member 88448601-Aug-13 1:57
Member 88448601-Aug-13 1:57 
AnswerRe: My vote of 1 Pin
Clifford Nelson3-Aug-13 12:51
Clifford Nelson3-Aug-13 12:51 
SuggestionMake it a tip or trick Pin
Julian Goldsmith30-Jul-13 10:02
Julian Goldsmith30-Jul-13 10:02 
AnswerRe: Make it a tip or trick Pin
Clifford Nelson30-Jul-13 10:25
Clifford Nelson30-Jul-13 10:25 
GeneralRe: Make it a tip or trick Pin
Julian Goldsmith1-Aug-13 3:26
Julian Goldsmith1-Aug-13 3:26 

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

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