Created
February 6, 2019 14:53
-
-
Save mjs3339/1068fd7fd2b8cdd55fe1dc23faa82778 to your computer and use it in GitHub Desktop.
C# IEnumerable File Helper Class, Load or Save Primitive, Class, Structure, IEnumerable To or From a File.
This file contains hidden or 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
/// <summary> | |
/// IEnumerable File Helper Class. | |
/// </summary> | |
public static class IEnumerableFileHelper | |
{ | |
/// <summary> | |
/// Save a IEnumerable to a file. | |
/// </summary> | |
public static void SaveToFileIEnum<T>(this IEnumerable<T> obj, string path, bool append = false) | |
{ | |
var type = obj.GetType(); | |
if(!type.IsSerializable) | |
throw new Exception("The object is not serializable."); | |
using(Stream stream = File.Open(path, append ? FileMode.Append : FileMode.Create)) | |
{ | |
var bf = new BinaryFormatter(); | |
bf.Serialize(stream, obj); | |
} | |
} | |
/// <summary> | |
/// Load a IEnumerable from a file. | |
/// </summary> | |
public static IEnumerable<T> LoadFromFileIEnum<T>(this IEnumerable<T> dump, string path) | |
{ | |
var type = dump.GetType(); | |
if(!type.IsSerializable) | |
throw new Exception("The object is not serializable."); | |
using(Stream stream = File.Open(path, FileMode.Open)) | |
{ | |
var bf = new BinaryFormatter(); | |
var obj = (IEnumerable<T>) bf.Deserialize(stream); | |
return obj; | |
} | |
} | |
/// <summary> | |
/// Save an object (Primitive, class, structure) to a file. | |
/// </summary> | |
public static void SaveToFileObj<T>(this T obj, string path, bool append = false) | |
{ | |
var type = obj.GetType(); | |
if(!type.IsSerializable) | |
throw new Exception("The object is not serializable."); | |
using(Stream stream = File.Open(path, append ? FileMode.Append : FileMode.Create)) | |
{ | |
var bf = new BinaryFormatter(); | |
bf.Serialize(stream, obj); | |
} | |
} | |
/// <summary> | |
/// Load an object (Primitive, class, structure) from a file. | |
/// </summary> | |
public static T LoadFromFileObj<T>(this T dump, string path) | |
{ | |
var type = dump.GetType(); | |
if(!type.IsSerializable) | |
throw new Exception("The object is not serializable."); | |
using(Stream stream = File.Open(path, FileMode.Open)) | |
{ | |
var bf = new BinaryFormatter(); | |
var obj = (T) bf.Deserialize(stream); | |
return obj; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment