即使在使用()中封装内存流也不可扩展

时间:2017-05-21 22:42:21

标签: c#

我正在使用多个内存流将我的文件名转换为流并将其写入其中:

#include <stdio.h>

#include "point.h"

int main(void) {
    struct point *point;

    point = point_alloc();

    point_setCoordinates(point, 1, 2);

    printf("Coordinates: X Coordinate: %f, Y Coordinate: %f\n",
           point_getXCoordinate(point),
           point_getYCoordinate(point));

    point_free(point);

    return 0;
}

但不知何故,当我致电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()

第290行是我呼叫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

的行

我不确定导致错误的原因!

2 个答案:

答案 0 :(得分:3)

您已创建一个内存流,该内存流从字符串 Clients.txt的utf8表示中读取,而不是从文件中读取。

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

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

答案 1 :(得分:1)

如果在MemoryStream字节数组上创建pre-allocated,则无法扩展(即,比您开始时指定的大小更长)

var length =Encoding.UTF8.GetBytes("Clients.txt");
  //    the length here is 11 bytes  

您正在预先分配buffer of 11个字节,而不是文件的长度,所以当您尝试读取大于11个字节的字符串时,您将收到错误

如果您需要获取文件的长度,则应使用FileInfo.Length