Skip to content

Instantly share code, notes, and snippets.

@ginomessmer
Created September 12, 2015 13:49
Show Gist options
  • Save ginomessmer/223e5b3ab2078c186bbf to your computer and use it in GitHub Desktop.
Save ginomessmer/223e5b3ab2078c186bbf to your computer and use it in GitHub Desktop.
Deserializes/serializes objects to output files as JSON. Built on top of C# 6, requires Json.NET
using Newtonsoft.Json;
using System.IO;
using System.Text;
// TODO: Namespace
/// <summary>
/// De- or serializes objects to output files as JSON.
/// </summary>
/// <typeparam name="T">Object type to save or load</typeparam>
public static class ObjectFileResourceController<T>
{
public static void SaveObjectToFile(T obj, string filePathName)
{
FileInfo ensureInfo = new FileInfo(filePathName);
EnsureFileSystemSetup(ensureInfo.Directory.FullName);
using (var writer = new StreamWriter(new FileStream(filePathName, FileMode.Create), Encoding.Unicode))
{
writer.Write(JsonConvert.SerializeObject(obj));
}
}
public static T LoadObjectFromFile(string filePathName)
{
FileInfo ensureInfo = new FileInfo(filePathName);
EnsureFileSystemSetup(ensureInfo.Directory.FullName, ensureInfo.Name);
using (var reader = new StreamReader(new FileStream(filePathName, FileMode.Open)))
{
return JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
}
}
public static void EnsureFileSystemSetup(string filePath, string fileName = "")
{
bool isFileNameSpecified = !string.IsNullOrEmpty(fileName);
if (isFileNameSpecified)
fileName = @"\" + fileName;
FileInfo info = new FileInfo($"{filePath}{fileName}");
if (!Directory.Exists(info.Directory.FullName))
Directory.CreateDirectory(info.Directory.FullName);
if (isFileNameSpecified)
{
if (!File.Exists(info.FullName))
File.WriteAllText(info.FullName, "");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment