From 3d41f0debbbff6f12dbb3462516d06fff72808dd Mon Sep 17 00:00:00 2001 From: Tom Padilla Date: Tue, 30 Oct 2018 12:55:12 +0000 Subject: [PATCH] Adding MockFileData overload to serialize objects --- .../MockFileData.cs | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/System.IO.Abstractions.TestingHelpers/MockFileData.cs b/System.IO.Abstractions.TestingHelpers/MockFileData.cs index 15aa84298..a9a87f5d5 100644 --- a/System.IO.Abstractions.TestingHelpers/MockFileData.cs +++ b/System.IO.Abstractions.TestingHelpers/MockFileData.cs @@ -1,6 +1,10 @@ using System.Linq; using System.Security.AccessControl; using System.Text; +#if NET40 || NETSTANDARD_20 +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters.Binary; +#endif namespace System.IO.Abstractions.TestingHelpers { @@ -78,7 +82,36 @@ public MockFileData(string textContents, Encoding encoding) /// Thrown if is . public MockFileData(byte[] contents) { - Contents = contents ?? throw new ArgumentNullException(nameof(contents)); + SetByteBuffer(contents); + } + +#if NET40 || NETSTANDARD_20 + + ///// + ///// Initializes a new instance of the class with the serialized content of . + ///// + ///// The actual content as an object. + ///// Thrown if is . + public MockFileData(object contents) + { + //Copy the object into byte array + MemoryStream stream = new MemoryStream(); + IFormatter formatter = new BinaryFormatter(); + formatter.Serialize(stream, contents); + + //Add the byte array as file data + SetByteBuffer(stream.GetBuffer()); + } +#endif + + /// + /// Unified method for setting byte buffer + /// + /// + /// Thrown if is . + private void SetByteBuffer(byte[] bufferContents) + { + Contents = bufferContents ?? throw new ArgumentNullException(nameof(bufferContents)); }