c# - 即使封装在 using() 中,内存流也不可扩展

标签 c#

我正在使用多个内存流将我的文件名转换为流并像这样写入它们:

public static void Save() {
    try {
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("Clients.txt"))) {
            using(StreamWriter sw = new StreamWriter(ms)) {
                writeClients(sw);
            } */ Line 91 */
        }

        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("Hotels.txt"))) {
            using(StreamWriter sw = new StreamWriter(ms)) {
                writeHotels(sw);
            }
        } 
        [...]
    } catch {
        [...]
    }
}

但不知何故,当我调用 Save() 时,出现以下错误:

Unhandled Exception: System.NotSupportedException: Memory stream is not expandable.
   at System.IO.__Error.MemoryStreamNotExpandable()
   at System.IO.MemoryStream.set_Capacity(Int32 value)
   at System.IO.MemoryStream.EnsureCapacity(Int32 value)
   at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
   at System.IO.StreamWriter.Dispose(Boolean disposing)
   at System.IO.TextWriter.Dispose()
   at csharp.Program.Save() in /home/nids/Documents/csharp/Program.cs:line 91
   at csharp.Program.Main(String[] args) in /home/nids/Documents/csharp/Program.cs:line 290

第 290 行是我调用 Save()

的行

我不确定是什么导致了错误!

最佳答案

您已经创建了一个内存流,它从 string Clients.txt 的 utf8 表示中读取,而不是从文件中读取。

包装固定字节数组的内存流是不可调整大小的,因此您不能写入超过初始化它们的字节数组的大小。

如果您打算写入文件,请参阅 How to Write to a file using StreamWriter?

关于c# - 即使封装在 using() 中,内存流也不可扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44102510/

相关文章:

c# - 尽管没有发生请求,但 TempData[] 被删除

c# - LINQ Varbinary 到 C# 字节数组

c# - 使用弹性数据库客户端库、EF 和 Identity 时找不到 DbContext

c# - 数据库连接关闭位置在try catch/using中

c# - 在RelativeLayout中动态绑定(bind)多个图像与MVVM?

c# - 开发类似于ASP.NET session 的系统时要考虑的安全性注意事项

c# - 第一个 html 帮助程序生成客户端验证属性,而第二个则不

C# 通用继承解决方法

c# - 如何在 C# 中的文本框中获取光标的列号?

c# - 如何在 jQuery 函数中使用 Windows Phone 8 C# 列表