How do I generate a stream from a string?
我需要为一个方法编写单元测试,该方法接受来自文本文件的流。 我想做这样的事情:
1 2 | Stream s = GenerateStreamFromString("a,b c,d"); |
1 2 3 4 5 6 7 8 9 |
别忘了使用:
1 2 3 4 5 | using (var stream = GenerateStreamFromString("a,b c,d")) { // ... Do stuff to stream } |
关于
在.NET 4.5中,现在有一个
请参阅是否有任何方法可以在不关闭其BaseStream的情况下关闭StreamWriter?
另一种方案:
1 2 3 4 | public static MemoryStream GenerateStreamFromString(string value) { return new MemoryStream(Encoding.UTF8.GetBytes(value ??"")); } |
将其添加到静态字符串实用程序类:
1 2 3 4 5 6 7 8 9 |
这会添加一个扩展功能,您可以简单地:
1 2 3 4 | using (var stringStream ="My string".ToStream()) { // use stringStream } |
1 2 3 4 | public Stream GenerateStreamFromString(string s) { return new MemoryStream(Encoding.UTF8.GetBytes(s)); } |
使用
你随后在流上需要
我使用了这样的答案:
1 2 3 4 5 | public static Stream ToStream(this string str, Encoding enc = null) { enc = enc ?? Encoding.UTF8; return new MemoryStream(enc.GetBytes(str ??"")); } |
然后我像这样使用它:
1 2 3 4 5 6 | String someStr="This is a Test"; Encoding enc = getEncodingFromSomeWhere(); using (Stream stream = someStr.ToStream(enc)) { // Do something with the stream.... } |
我们使用下面列出的扩展方法。我认为你应该让开发人员对编码做出决定,因此所涉及的魔法就更少了。
1 2 3 4 5 6 7 8 9 10 | 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 ??"")); } } |
干得好:
1 2 3 4 5 6 7 | private Stream GenerateStreamFromString(String p) { Byte[] bytes = UTF8Encoding.GetBytes(p); MemoryStream strm = new MemoryStream(); strm.Write(bytes, 0, bytes.Length); return strm; } |
1 2 3 4 | public static Stream ToStream(this string value) => ToStream(value, Encoding.UTF8); public static Stream ToStream(this string value, Encoding encoding) => new MemoryStream(encoding.GetBytes(value ?? string.Empty)); |
@ Palec对@Shaun Bowe回答的评论中提出的修改。
我想你可以从使用MemoryStream中受益。您可以使用Encoding类的GetBytes方法填充您获得的字符串字节。
如果您需要更改编码,我会投票给@ ShaunBowe的解决方案。但是这里的每个答案都会将整个字符串复制到内存中至少一次。
如果这里重要的是原始UTF-16字符串的简单
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | public class StringStream : Stream { private readonly string str; public override bool CanRead => true; public override bool CanSeek => true; public override bool CanWrite => false; public override long Length => str.Length * 2; public override long Position { get; set; } // TODO: bounds check public StringStream(string s) => str = s ?? throw new ArgumentNullException(nameof(s)); public override long Seek(long offset, SeekOrigin origin) { switch (origin) { case SeekOrigin.Begin: Position = offset; break; case SeekOrigin.Current: Position += offset; break; case SeekOrigin.End: Position = Length - offset; break; } return Position; } private byte this[int i] => (i & 1) == 0 ? (byte)(str[i / 2] & 0xFF) : (byte)(str[i / 2] >> 8); public override int Read(byte[] buffer, int offset, int count) { // TODO: bounds check var len = Math.Min(count, Length - Position); for (int i = 0; i < len; i++) buffer[offset++] = this[(int)(Position++)]; return (int)len; } public override int ReadByte() => Position >= Length ? -1 : this[(int)Position++]; public override void Flush() { } public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); public override string ToString() => str; // ;) } |
这里有一个更完整的解决方案,带有必要的绑定检查(从
String扩展的良好组合:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | /// <summary> /// Get Byte[] from String /// </summary> /// <param name="str"></param> /// <returns></returns> public static byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } /// <summary> /// Get Stream from String /// </summary> /// <param name="str"></param> /// <returns></returns> public static Stream GetStream(string str) { return new MemoryStream(GetBytes(str)); } |