Skip to content

Instantly share code, notes, and snippets.

@mjs3339
Created February 6, 2019 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjs3339/1068fd7fd2b8cdd55fe1dc23faa82778 to your computer and use it in GitHub Desktop.
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.
/// <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