Skip to content

Instantly share code, notes, and snippets.

@pedropombeiro
Last active December 19, 2015 15:09
Show Gist options
  • Save pedropombeiro/5974776 to your computer and use it in GitHub Desktop.
Save pedropombeiro/5974776 to your computer and use it in GitHub Desktop.
/// <summary>
/// Deserializes a file from within a ZIP archive using the <see cref="BinaryFormatter"/> and passing a specified context object.
/// </summary>
/// <param name="zipFilePath">
/// The ZIP file path.
/// </param>
/// <param name="entryPath">
/// The path of the file to deserialize within the ZIP file.
/// </param>
/// <param name="deserializationContext">
/// The deserialization context (will be passed to the deserialized object's constructor in <see cref="StreamingContext.Context"/>).
/// </param>
/// <returns>
/// The deserialized object.
/// </returns>
/// <exception cref="FileNotFoundException">
/// Thrown when the file at <paramref name="zipFilePath"/> does not exist.
/// </exception>
public object DeserializeFrom(string zipFilePath,
string entryPath,
object deserializationContext)
{
if (!this.file.Exists(zipFilePath))
{
throw new FileNotFoundException(string.Format("Could not open '{0}'", zipFilePath));
}
using (var zipFile = new ZipFile(zipFilePath))
{
using (var stream = zipFile[entryPath].OpenReader())
{
var binaryFormatter = new BinaryFormatter { Context = new StreamingContext(StreamingContextStates.Persistence, deserializationContext) };
return binaryFormatter.Deserialize(stream);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment