views:

210

answers:

6

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

Stream s = GenerateStreamFromString("a,b \n c,d");
+5  A: 

Use the MemoryStream class, calling Encoding.GetBytes to turn your string into an array of bytes first.

Do you subsequently need a TextReader on the stream? If so, you could supply a StringReader directly, and bypass the MemoryStream and Encoding steps.

Tim Robinson
yes, I do need a textreader
Omu
+3  A: 

I think you can benefit from using a MemoryStream. You can fill it with the string bytes that you obtain by using the GetBytes method of the Encoding class.

Konamiman
+4  A: 

You're looking for the StringReader class.

Well, maybe not directly, but i bet you want to use that stream in some sort fo reader right? if so, then you could use that directly.

RCIX
yes I need a textreader after
Omu
This is incorrect. StringReader cannot return a Stream from a string. StringReader enables you to access string data through a stream *oriented* interface. In other words, it simply allows you to process the string as if it was a stream. This confusion stems from bad naming on Microsoft behalf for the StreamReader/StreamWriter classes, which also actually have no direct realtionship to the Stream classes. Note that TextReader/TextWriter (the base classes) have no conversion to/from Stream and do not inherit from Stream.
Ash
+3  A: 

Try stringreader http://msdn.microsoft.com/en-us/library/system.io.stringreader.aspx

Also this blog has a few ideas as well: http://weblogs.asp.net/whaggard/archive/2004/09/23/233535.aspx

RedDeckWins
This is incorrect. StringReader cannot return a Stream from a string. StringReader enables you to access string data through a stream oriented interface. In other words, it simply allows you to process the string as if it was a stream. This confusion stems from bad naming on Microsoft behalf for the StreamReader/StreamWriter classes, which also actually have no direct realtionship to the Stream classes. Note that TextReader/TextWriter (the base classes) have no conversion to/from Stream and do not inherit from Stream
Ash
+3  A: 

Here you go:

private Stream GenerateStreamFromString(String p)
{
    Byte[] bytes = UTF8Encoding.GetBytes(p);
    MemoryStream strm = new MemoryStream();
    strm.Write(bytes, 0, bytes.Length);
    return strm;
}
ck
+5  A: 
public Stream GenerateStreamFromString(string s)
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(s);
    writer.Flush();
    stream.Position = 0;
    return stream;
}

Don't forget to use Using:

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