Mohanapriya R Mohanapriya R
Updated date May 05, 2024
In this article, we will learn how to convert strings to streams in C#.

Convert Strings to Stream in C#:

In C#, a stream is a sequence of bytes, and converting a string into a stream allows for efficient handling of data. This conversion is particularly useful when dealing with I/O operations, such as reading from or writing to files, network communication, or working with other data sources.

Program:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Input string
        string inputString = "Hello, C# String-to-Stream Conversion!";

        // Convert string to byte array
        byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(inputString);

        // Create a MemoryStream from the byte array
        using (MemoryStream stream = new MemoryStream(byteArray))
        {
            // Read the stream and display the output
            using (StreamReader reader = new StreamReader(stream))
            {
                string output = reader.ReadToEnd();
                Console.WriteLine("Output from Stream: " + output);
            }
        }
    }
}
  • We start with a sample string, "Hello, C# String-to-Stream Conversion!"
  • The string is converted into a byte array using UTF-8 encoding.
  • A MemoryStream is created using the byte array.
  • A StreamReader is then used to read from the stream.
  • The output is displayed on the console.

Output:

Output from Stream: Hello, C# String-to-Stream Conversion!

The program successfully converts the input string into a stream and retrieves the original string from the stream.

Comments (0)

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