Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a stream from a string?

I need to write a unit test for a method that takes a stream which comes from a text file. I would like to do do something like this:

Stream s = GenerateStreamFromString("a,b \n c,d"); 
like image 435
Omu Avatar asked Dec 10 '09 08:12

Omu


People also ask

Can we convert string to stream?

To convert a string to a stream you need to decide which encoding the bytes in the stream should have to represent that string - for example you can: MemoryStream mStrm= new MemoryStream( Encoding. UTF8. GetBytes( contents ) );

Is a string a stream?

A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input.

What is stream C#?

The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation).


1 Answers

public static Stream GenerateStreamFromString(string s) {     var stream = new MemoryStream();     var writer = new StreamWriter(stream);     writer.Write(s);     writer.Flush();     stream.Position = 0;     return stream; } 

Don't forget to use Using:

using (var stream = GenerateStreamFromString("a,b \n c,d")) {     // ... Do stuff to stream } 

About the StreamWriter not being disposed. StreamWriter is just a wrapper around the base stream, and doesn't use any resources that need to be disposed. The Dispose method will close the underlying Stream that StreamWriter is writing to. In this case that is the MemoryStream we want to return.

In .NET 4.5 there is now an overload for StreamWriter that keeps the underlying stream open after the writer is disposed of, but this code does the same thing and works with other versions of .NET too.

See Is there any way to close a StreamWriter without closing its BaseStream?

like image 174
Cameron MacFarland Avatar answered Sep 29 '22 22:09

Cameron MacFarland