How do I generate a stream from a string?

后端 未结 12 842
春和景丽
春和景丽 2020-11-22 14:29

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         


        
12条回答
  •  眼角桃花
    2020-11-22 15:16

    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
    }
    

提交回复
热议问题