How do I generate a stream from a string?

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

    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.

    0 讨论(0)
  • 2020-11-22 15:31

    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....
    }
    
    0 讨论(0)
  • 2020-11-22 15:32

    Another solution:

    public static MemoryStream GenerateStreamFromString(string value)
    {
        return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
    }
    
    0 讨论(0)
  • 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 ?? ""));
        }
    }
    
    0 讨论(0)
  • 2020-11-22 15:36

    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;
    }
    
    0 讨论(0)
  • 2020-11-22 15:36

    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.

    0 讨论(0)
提交回复
热议问题