Skip to content

Instantly share code, notes, and snippets.

@jpdillingham
Created November 16, 2016 17:36
Show Gist options
  • Save jpdillingham/dceb3da7519bbd9db7478bf0b8e623a5 to your computer and use it in GitHub Desktop.
Save jpdillingham/dceb3da7519bbd9db7478bf0b8e623a5 to your computer and use it in GitHub Desktop.
/// <summary>
/// Serializes the specified object to json and writes the resulting text to the specified file.
/// If the destination file exists, it is overwritten if the overwrite flag is set to true.
/// </summary>
/// <param name="obj">The object to serialize.</param>
/// <param name="fileName">The file to write.</param>
/// <param name="overwrite">True if the specified file is to be overwritten if it exists, false otherwise.</param>
/// <returns>True if the operation succeeded.</returns>
/// <exception cref="FileLoadException">Thrown if the specified file exists and the overwrite flag is false.</exception>
/// <exception cref="JsonException">Thrown if an exception is encountered while serializing the specified object.</exception>
/// <exception cref="IOException">Thrown if an exception is encountered while saving the output file.</exception>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed.")]
private bool SaveJson(object obj, string fileName, bool overwrite = false)
{
if (File.Exists(fileName) && !overwrite)
{
throw new FileLoadException("The file '" + fileName + "' already exists and will not be overwritten.");
}
else
{
string objJson;
// try to serialize the recipe to a string
try
{
objJson = JsonConvert.SerializeObject(obj, Formatting.Indented);
}
catch (Exception ex)
{
logger.Info("Exception caught while serializing recipe: " + ex.Message);
throw new JsonException("Error serializing recipe. See inner exception for details.", ex);
}
// try to save the string to the specified file
try
{
File.WriteAllText(fileName, objJson);
}
catch (Exception ex)
{
logger.Info("Exception caught while writing output file: " + ex.Message);
throw new IOException("Error saving file. See inner exception for details.", ex);
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment