How do I generate a stream from a string?

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

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

提交回复
热议问题