Created
March 8, 2011 22:51
-
-
Save nrkn/861282 to your computer and use it in GitHub Desktop.
Save/load arbitrary .NET objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using System.Runtime.Serialization.Formatters.Binary; | |
namespace LosvRLLib { | |
/// <summary> | |
/// Usage: | |
/// <![CDATA[ | |
/// var mapPersistence = new Persistence<Map>(); | |
/// var map = mapPersistence.Load( "map.dat" ); | |
/// | |
/// //do something to map here | |
/// | |
/// mapPersistence.Save( map, "map.dat" ); | |
/// ]]> | |
/// </summary> | |
/// <typeparam name="T">The type of object to load/save</typeparam> | |
public class Persistence<T> where T : class { | |
public T Load( string name ) | |
{ | |
var formatter = new BinaryFormatter(); | |
var stream = new FileStream( name, FileMode.Open, FileAccess.Read, FileShare.Read ); | |
var obj = (T)formatter.Deserialize(stream); | |
stream.Close(); | |
return obj; | |
} | |
public void Save( T obj, string name ) | |
{ | |
var formatter = new BinaryFormatter(); | |
var stream = new FileStream( name, FileMode.Create, FileAccess.Write, FileShare.None ); | |
formatter.Serialize( stream, obj ); | |
stream.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment