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)); }