This extension class is useful when you want to create a stream from some bytes of directly from a string
public static class StreamExtender
{
/// <summary>
/// Create a stream from an array of bytes
/// </summary>
/// <param name="streamBytes">Bytes source foe the stream</param>
/// <returns></returns>
public static MemoryStream CreateStreamFromBytes(this byte[] streamBytes)
{
var stream = new MemoryStream();
stream.Write(streamBytes, 0, streamBytes.Length);
stream.Seek(0, 0);
return stream;
}
/// <summary>
/// Create a stream from a string
/// </summary>
/// <remarks>Useful for unit testing file storage</remarks>
/// <param name="contents">The contents to be placed in the stream</param>
/// <returns>A memory stream with the string as contents</returns>
public static MemoryStream CreateStreamFromString(this string contents)
{
byte[] encodedStreamBytes = Encoding.UTF8.GetBytes(contents);
var stream CreateStreamFromBytes(encodedStreamBytes);
return stream;
}
}
No comments:
Post a Comment