我需要为一个方法编写一个单元测试,该方法采用来自文本文件的流。我想做这样的事情:
Stream s = GenerateStreamFromString("a,b \n c,d");
我需要为一个方法编写一个单元测试,该方法采用来自文本文件的流。我想做这样的事情:
Stream s = GenerateStreamFromString("a,b \n c,d");
当前回答
另一个解决方案:
public static MemoryStream GenerateStreamFromString(string value)
{
return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
}
其他回答
使用MemoryStream类,调用Encoding。GetBytes首先将字符串转换为字节数组。
您随后是否需要流上的TextReader ?如果是这样,您可以直接提供一个StringReader,并绕过MemoryStream和Encoding步骤。
另一个解决方案:
public static MemoryStream GenerateStreamFromString(string value)
{
return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
}
将此添加到静态字符串实用程序类:
public static Stream ToStream(this string str)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(str);
writer.Flush();
stream.Position = 0;
return stream;
}
这增加了一个扩展函数,所以你可以简单地:
using (var stringStream = "My string".ToStream())
{
// use stringStream
}
我使用了如下的混合答案:
public static Stream ToStream(this string str, Encoding enc = null)
{
enc = enc ?? Encoding.UTF8;
return new MemoryStream(enc.GetBytes(str ?? ""));
}
然后我这样使用它:
String someStr="This is a Test";
Encoding enc = getEncodingFromSomeWhere();
using (Stream stream = someStr.ToStream(enc))
{
// Do something with the stream....
}
String扩展的良好组合:
public static byte[] GetBytes(this string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static Stream ToStream(this string str)
{
Stream StringStream = new MemoryStream();
StringStream.Read(str.GetBytes(), 0, str.Length);
return StringStream;
}