Mohanapriya R Mohanapriya R
Updated date May 18, 2024
In this article, we will explore how to convert Strings to MemoryStream in C#.
  • 2.6k
  • 0
  • 0

Convert Strings to MemoryStream in C#

using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        // Sample string for conversion
        string inputString = "Hello, this is a sample string for MemoryStream conversion.";

        // Convert string to MemoryStream
        MemoryStream memoryStream = ConvertStringToMemoryStream(inputString);

        // Display the content of the MemoryStream
        DisplayMemoryStreamContent(memoryStream);
    }

    static MemoryStream ConvertStringToMemoryStream(string inputString)
    {
        // Convert string to byte array
        byte[] byteArray = Encoding.UTF8.GetBytes(inputString);

        // Create MemoryStream from the byte array
        MemoryStream memoryStream = new MemoryStream(byteArray);

        return memoryStream;
    }

    static void DisplayMemoryStreamContent(MemoryStream memoryStream)
    {
        // Display the content of the MemoryStream
        Console.WriteLine("MemoryStream Content:");
        Console.WriteLine(Encoding.UTF8.GetString(memoryStream.ToArray()));
    }
}

The code above uses the Encoding.UTF8.GetBytes() method to convert the input string into a byte array. Later, a MemoryStream is created using this byte array. Finally, the content of the MemoryStream is displayed by converting it back to a string.

Output:

MemoryStream Content:
Hello, this is a sample string for MemoryStream conversion.

Comments (0)

There are no comments. Be the first to comment!!!