Mohanapriya R Mohanapriya R
Updated date May 08, 2024
In this article, we will learn how to convert a MemoryStream into strings in C#.
  • 2.3k
  • 0
  • 0

Convert MemoryStream to Strings in C#

C# program that shows the conversion of a MemoryStream to strings:

In this program, we start by creating a MemoryStream and writing a sample string to it. The ConvertMemoryStreamToString method is then called to convert the MemoryStream into a string. It's crucial to reset the position of the MemoryStream to the beginning before reading it, ensuring that the entire content is read.

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

class Program
{
    static void Main()
    {
        // Create a MemoryStream
        using (MemoryStream memoryStream = new MemoryStream())
        {
            // Write data to the MemoryStream
            byte[] data = Encoding.UTF8.GetBytes("Hello, MemoryStream to String Conversion!");
            memoryStream.Write(data, 0, data.Length);

            // Convert MemoryStream to string
            string resultString = ConvertMemoryStreamToString(memoryStream);

            // Display the result
            Console.WriteLine("Converted String: " + resultString);
        }
    }

    static string ConvertMemoryStreamToString(MemoryStream memoryStream)
    {
        // Reset the position of the MemoryStream
        memoryStream.Position = 0;

        // Read the MemoryStream and convert to string
        using (StreamReader reader = new StreamReader(memoryStream, Encoding.UTF8))
        {
            return reader.ReadToEnd();
        }
    }
}

Output:

Converted String: Hello, MemoryStream to String Conversion!

Comments (0)

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