How do I generate a stream from a string?

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

    A good combination of String extensions:

    public static byte[] GetBytes(this string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }
    
    public static Stream ToStream(this string str)
    {
        Stream StringStream = new MemoryStream();
        StringStream.Read(str.GetBytes(), 0, str.Length);
        return StringStream;
    }
    

提交回复
热议问题