Click here to Skip to main content
14,022,795 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

44.2K views
49 bookmarked
Posted 25 Jul 2013
Licenced CPOL

Serializing to a File

, 30 Jul 2013
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:

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:

/// <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)

Share

About the Author

Clifford Nelson
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.

You may also be interested in...

Comments and Discussions

 
QuestionGood Article Pin
Mike DiRenzo6-Nov-13 5:24
memberMike DiRenzo6-Nov-13 5:24 
AnswerRe: Good Article Pin
Clifford Nelson6-Nov-13 7:05
mvaClifford Nelson6-Nov-13 7:05 
GeneralMy vote of 1 Pin
Yet Another XCoder15-Aug-13 23:56
memberYet Another XCoder15-Aug-13 23:56 
AnswerRe: My vote of 1 Pin
Clifford Nelson16-Aug-13 0:26
mvaClifford Nelson16-Aug-13 0:26 
GeneralRe: My vote of 1 Pin
Yet Another XCoder16-Aug-13 1:07
memberYet Another XCoder16-Aug-13 1:07 
GeneralRe: My vote of 1 Pin
Rob Philpott16-Aug-13 22:28
memberRob Philpott16-Aug-13 22:28 
GeneralRe: My vote of 1 Pin
Yet Another XCoder17-Aug-13 22:45
memberYet Another XCoder17-Aug-13 22:45 
GeneralRe: My vote of 1 Pin
Rob Philpott18-Aug-13 0:28
memberRob Philpott18-Aug-13 0:28 
GeneralRe: My vote of 1 Pin
Yet Another XCoder18-Aug-13 0:50
memberYet 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
memberdb7uk12-Aug-13 20:48 
AnswerRe: Thanks Pin
Clifford Nelson13-Aug-13 5:05
mvaClifford Nelson13-Aug-13 5:05 
GeneralVote of 5 Pin
Simon_Whale11-Aug-13 23:01
professionalSimon_Whale11-Aug-13 23:01 
AnswerRe: Vote of 5 Pin
Clifford Nelson12-Aug-13 6:30
mvaClifford Nelson12-Aug-13 6:30 
PraiseRe: Vote of 5 Pin
Clifford Nelson17-Aug-16 5:12
mvaClifford Nelson17-Aug-16 5:12 
GeneralMy vote of 4 Pin
Cindy Meister10-Aug-13 6:03
memberCindy Meister10-Aug-13 6:03 
GeneralMy vote of 2 Pin
Danielvrhyn8-Aug-13 2:31
memberDanielvrhyn8-Aug-13 2:31 
AnswerRe: My vote of 2 Pin
Clifford Nelson8-Aug-13 5:32
mvaClifford Nelson8-Aug-13 5:32 
GeneralMy vote of 1 Pin
Member 88448601-Aug-13 1:57
memberMember 88448601-Aug-13 1:57 
AnswerRe: My vote of 1 Pin
Clifford Nelson3-Aug-13 12:51
mvaClifford Nelson3-Aug-13 12:51 
SuggestionMake it a tip or trick Pin
Julian Goldsmith30-Jul-13 10:02
memberJulian Goldsmith30-Jul-13 10:02 
AnswerRe: Make it a tip or trick Pin
Clifford Nelson30-Jul-13 10:25
mvaClifford Nelson30-Jul-13 10:25 
GeneralRe: Make it a tip or trick Pin
Julian Goldsmith1-Aug-13 3:26
memberJulian 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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190417.4 | Last Updated 30 Jul 2013
Article Copyright 2013 by Clifford Nelson
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid