c# - 将字符串转换为内存流 - 内存流不可扩展?

标签 c# memorystream

我试图将字符串写入内存流, 但失败并显示错误消息:

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/

相关文章:

c# - 如果在 ASP.NET 中不存在,sql server 的用法?

C# SCCM - 客户端操作

c# - List<T> 来自 List<T> 中的属性

c# - 从 C# 中的巨大 MemoryStream 中读取

c# - 内存泄漏 - 使用 MemoryStream 从尼康相机捕获实时视频

c# - 切换枚举自动填充

c# - 重载 protected 通用方法单元测试导致 AmbigeousMatchException

c# - 优点/缺点 MemoryStream.Position 或 MemoryStream.Seek

c# - 从内存流中删除数据

.net - MemoryStream 使用了多少内存?