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 = GenerateStre
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.
I used a mix of answers like this:
public static Stream ToStream(this string str, Encoding enc = null)
{
enc = enc ?? Encoding.UTF8;
return new MemoryStream(enc.GetBytes(str ?? ""));
}
And then I use it like this:
String someStr="This is a Test";
Encoding enc = getEncodingFromSomeWhere();
using (Stream stream = someStr.ToStream(enc))
{
// Do something with the stream....
}
Another solution:
public static MemoryStream GenerateStreamFromString(string value)
{
return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
}
We use the extension methods listed below. I think you should make the developer make a decision about the encoding, so there is less magic involved.
public static class StringExtensions {
public static Stream ToStream(this string s) {
return s.ToStream(Encoding.UTF8);
}
public static Stream ToStream(this string s, Encoding encoding) {
return new MemoryStream(encoding.GetBytes(s ?? ""));
}
}
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;
}
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.