How do I generate a stream from a string?

2019-01-01 06:32发布

问题:

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\");

回答1:

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.

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.

See Is there any way to close a StreamWriter without closing its BaseStream?



回答2:

Another solution:

public static MemoryStream GenerateStreamFromString(string value)
{
    return new MemoryStream(Encoding.UTF8.GetBytes(value ?? \"\"));
}


回答3:

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
}


回答4:

public Stream GenerateStreamFromString(string s)
{
    return new MemoryStream(Encoding.UTF8.GetBytes(s));
}


回答5:

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.



回答6:

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....
}


回答7:

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;
}


回答8:

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 ?? \"\"));
    }
}


回答9:

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.



回答10:

Slightly modified version of the extension methods suggested in a comment of @JoelNet\'s answer and @Shaun Bowe answer. Because I agree with @Palec\'s comment.

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));


回答11:

/// <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));
}


回答12:

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;
}