convert string to memory stream - Memory stream is not expandable?

后端 未结 4 1596
忘掉有多难
忘掉有多难 2021-02-06 22:21

i was trying to write a string to a memory stream, but failed with the error message:

Memory stream is not expandable.

the line of code that pr

4条回答
  •  情书的邮戳
    2021-02-06 22:40

    The following code works correctly for me

    public class Foo
    {
        public static void Main()
        {
            var myPage = "test string";
            var repo =  new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(myPage));
        }
    }
    

    It seems that the correct way to do this is to create the MemoryStream using the default constructor

    var repo = new System.IO.MemoryStream();
    

    and then write to it

    var stringBytes = System.Text.Encoding.UTF8.GetBytes(myPage);
    repo.Write(stringBytes, 0, stringBytes.Length);
    

    if you want to be able to read the stream as normal (eg using a StreamReader) then you will also need to call:

    repo.Seek(0, SeekOrigin.Begin);
    

提交回复
热议问题