我使用多个内存流将文件名转换为流,并在其中写入,如下所示:
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()的行
我不知道是什么导致了这个错误!
发布于 2017-05-21 22:46:01
您已经创建了一个内存流,它从字符串 Clients.txt的表示形式中读取,而不是从文件中读取。
封装固定字节数组的内存流是不可调整大小的,因此不能写入比您使用的字节数组更大的大小。
如果您的目的是写入文件,请参阅How to Write to a file using StreamWriter?
发布于 2017-05-21 22:49:57
如果您在一个MemoryStream字节数组上创建一个pre-allocated,它就无法展开(即。比启动时指定的大小长)
var length =Encoding.UTF8.GetBytes("Clients.txt");
// the length here is 11 bytes 您正在预先分配一个buffer of 11字节,而不是文件的长度,因此当您试图读取高于11个字节的字符串时,您将得到一个错误。
如果需要获取文件的长度,则应使用FileInfo.Length
https://stackoverflow.com/questions/44102510
复制相似问题