C# 如何从字符串生成流?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1879395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I generate a stream from a string?
提问by Omu
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");
采纳答案by Cameron MacFarland
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.
关于StreamWriter
未处理。StreamWriter
只是基本流的包装器,不使用任何需要处理的资源。该Dispose
方法将关闭底层Stream
是StreamWriter
被写入。在这种情况下,这就是MemoryStream
我们想要返回的。
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.
在 .NET 4.5 中,现在有一个重载,用于StreamWriter
在处理写入器后保持底层流打开,但此代码执行相同的操作并且也适用于其他版本的 .NET。
See Is there any way to close a StreamWriter without closing its BaseStream?
回答by Tim Robinson
Use the MemoryStream
class, calling Encoding.GetBytes
to turn your string into an array of bytes first.
使用MemoryStream
该类,首先调用Encoding.GetBytes
将字符串转换为字节数组。
Do you subsequently need a TextReader
on the stream? If so, you could supply a StringReader
directly, and bypass the MemoryStream
and Encoding
steps.
您随后需要TextReader
在流中使用吗?如果是这样,您可以StringReader
直接提供 a ,并绕过MemoryStream
和Encoding
步骤。
回答by Konamiman
I think you can benefit from using a MemoryStream. You can fill it with the string bytes that you obtain by using the GetBytesmethod of the Encoding class.
我认为您可以从使用MemoryStream 中受益。您可以使用Encoding 类的GetBytes方法获取的字符串字节填充它。
回答by cjk
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;
}
回答by joelnet
Another solution:
另一种解决方案:
public static MemoryStream GenerateStreamFromString(string value)
{
return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
}
回答by Josh G
Add this to a static string utility class:
将此添加到静态字符串实用程序类:
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;
}
This adds an extension function so you can simply:
这增加了一个扩展功能,因此您可以简单地:
using (var stringStream = "My string".ToStream())
{
// use stringStream
}
回答by MarkWalls
A good combination of String extensions:
字符串扩展的良好组合:
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;
}
回答by Warlock
public Stream GenerateStreamFromString(string s)
{
return new MemoryStream(Encoding.UTF8.GetBytes(s));
}
回答by Robocide
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....
}
回答by Shaun Bowe
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 ?? ""));
}
}