How do I generate a stream from a string?

后端 未结 12 834
春和景丽
春和景丽 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:29

    Modernized and slightly modified version of the extension methods for ToStream:

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

    Modification as suggested in @Palec's comment of @Shaun Bowe answer.

提交回复
热议问题