How to convert a string to a stream, without using encoding in C#

If you want to convert a string to a stream, without using encoding. You can use the following string extension:

 

usage

namespace PTB.Cs.Test.Research
{
using PTB.Cs.Extensions;
using System;
using System.IO;
using Xunit;
public class RliTester
{
[Fact]
public void Test()
{
string subject = "Some text.";
long expected = 10;
long actual = 0;
using (Stream stream = subject.ToStream())
{
actual = stream.Length;
}    
Assert.Equal(expected, actual);
}
}
}

Code

namespace Extensions
{
using System.IO;
public static class StringExtensions
{
/// <summary>
/// Convert a string to a stream, without using encoding.
/// Don't forget to dispose the "result" stream in the calling method.
/// </summary>
/// <param name="subject">The string to convert.</param>
/// <returns>A stream with position set to 0.</returns>
public static Stream ToStream(this string subject)
{
var result = new MemoryStream();
using(var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
{
writer.Write(subject);
writer.Flush();
stream.Position = 0;
stream.CopyTo(result);
result.Position = 0;
}
return result;
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

One comment

  1. Fernando Pires says:

    Does this not use UTF-8 as default?