Showing posts with label Extension. Show all posts
Showing posts with label Extension. Show all posts

April 16, 2025

Stream Extension Class

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

October 25, 2019

Expand Environment Variables Extension

An extension to expand environment variables within a string

namespace Common.Environment.EnvironmentVariableExtension
{
  public static class StringEnvironmentVariableExtension
  {
    public static string ExpandEnvironmentVariables(this string path)
    {
        Debug.Assert(path != null);
        string result = "";
        result = Environment.ExpandEnvironmentVariables(path);
        return result;
    }
  }
}
and usage
using Common.Environment.EnvironmentVariableExtension;

[Test]
public void ExpandEnvironmentVariablesUsage()
{
    string path = "%Temp%";
    string tempPath = path.ExpandEnvironmentVariables();
}