2017-01-07 17:35:56 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Runtime.Serialization.Formatters.Binary;
|
2017-07-18 19:43:34 +00:00
|
|
|
|
|
|
|
|
|
namespace Nibriboard.Utilities
|
2017-01-07 17:35:56 +00:00
|
|
|
|
{
|
2017-07-18 19:43:34 +00:00
|
|
|
|
public static class BinaryIO
|
2017-01-07 17:35:56 +00:00
|
|
|
|
{
|
2017-07-15 21:41:31 +00:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// Deserialises an object from it's binary representation.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <typeparam name="T">The type to cast the deseralised object into.</typeparam>
|
|
|
|
|
/// <param name="sourceStream">The source stream to deseralise an object from.</param>
|
|
|
|
|
/// <returns>The object deserialised from the given stream.</returns>
|
2017-01-07 17:35:56 +00:00
|
|
|
|
public static async Task<T> DeserialiseBinaryObject<T>(Stream sourceStream)
|
|
|
|
|
{
|
|
|
|
|
return await Task.Run(() => {
|
|
|
|
|
BinaryFormatter formatter = new BinaryFormatter();
|
|
|
|
|
return (T)formatter.Deserialize(sourceStream);
|
|
|
|
|
});
|
|
|
|
|
}
|
2017-07-15 21:41:31 +00:00
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Serialises an object and outputs a binary representation to the given stream.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="target">The target to serialise.</param>
|
|
|
|
|
/// <param name="destinationStream">The destination stream to send the binary representation to.</param>
|
|
|
|
|
public static async Task SerialiseToBinary(object target, Stream destinationStream)
|
|
|
|
|
{
|
|
|
|
|
await Task.Run(() => {
|
|
|
|
|
BinaryFormatter formatter = new BinaryFormatter();
|
|
|
|
|
formatter.Serialize(destinationStream, target);
|
|
|
|
|
});
|
|
|
|
|
}
|
2017-01-07 17:35:56 +00:00
|
|
|
|
}
|
|
|
|
|
}
|