Last active
June 24, 2025 20:10
-
-
Save wantedfast/4ff443025dcddc677a28e311f30767ce to your computer and use it in GitHub Desktop.
C# Convert String to Stream, and Stream to String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| **Convert String to Stream** | |
| To convert a C# String to a MemoryStream object, use the GetBytes Encoding method to create a byte array, then pass that to the MemoryStream constructor: | |
| - byte[] byteArray = Encoding.ASCII.GetBytes( test ); | |
| - MemoryStream stream = new MemoryStream( byteArray ); | |
| **Convert Stream to String** | |
| To convert a Stream object (or any of its derived streams) to a C# String, create a StreamReader object, then call the ReadToEnd method: | |
| - StreamReader reader = new StreamReader( stream ); | |
| - string text = reader.ReadToEnd(); | |
| **Console Test Program** | |
| Here is a simple test program to demonstrate this round-trip conversion: | |
| using System; | |
| using System.IO; | |
| using System.Text; | |
| namespace CSharp411 | |
| { | |
| class Program | |
| { | |
| static void Main( string[] args ) | |
| { | |
| string test = "Testing 1-2-3"; | |
| // convert string to stream | |
| byte[] byteArray = Encoding.ASCII.GetBytes( test ); | |
| MemoryStream stream = new MemoryStream( byteArray ); | |
| // convert stream to string | |
| StreamReader reader = new StreamReader( stream ); | |
| string text = reader.ReadToEnd(); | |
| Console.WriteLine( text ); | |
| Console.ReadLine(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment