How do I generate a stream from a string?

后端 未结 12 848
春和景丽
春和景丽 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: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....
    }
    

提交回复
热议问题