0 Comments

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

One Reply to “How to convert a string to a stream, without using encoding in C#”

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

The 4 JavaScript load opportunities

0 Comments

Interesting podcast by Scott Hanselman and Nicholas Zakas: http://hanselminutes.com/383/enough-with-the-javascript-already-with-nicholas-zakas  …