我试图将字符串写入内存流, 但失败并显示错误消息:
Memory stream is not expandable.
产生这个问题的代码行:
context.Response.Filter = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(myPage));
有人对此有解决方法/修复方法吗?
堆栈跟踪:
[NotSupportedException: Memory stream is not expandable.]
System.IO.MemoryStream.set_Capacity(Int32 value) +9385744
System.IO.MemoryStream.EnsureCapacity(Int32 value) +50
System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) +265
System.Web.HttpWriter.FilterIntegrated(Boolean finalFiltering, IIS7WorkerRequest wr) +9155697
System.Web.HttpResponse.FilterOutput() +159
System.Web.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +52
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
最佳答案
下面的代码对我来说是正确的
public class Foo
{
public static void Main()
{
var myPage = "test string";
var repo = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(myPage));
}
}
似乎正确的方法是使用默认构造函数创建MemoryStream
var repo = new System.IO.MemoryStream();
然后写入
var stringBytes = System.Text.Encoding.UTF8.GetBytes(myPage);
repo.Write(stringBytes, 0, stringBytes.Length);
如果您希望能够正常读取流(例如使用 StreamReader),那么您还需要调用:
repo.Seek(0, SeekOrigin.Begin);
关于c# - 将字符串转换为内存流 - 内存流不可扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8097152/