1

I am using multiple memory streams to convert my file names to stream and write in them like so:

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 {
        [...]
    }
}

but somehow when I call Save() I get the following error:

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

Where line 290 is the line where I call Save()

I'm not sure what's causing the error!

Meryem
  • 477
  • 7
  • 17

2 Answers2

3

You have created a memory stream that reads from the utf8 representation of the string Clients.txt, not from a file.

Memory streams that wrap a fixed byte array are non-resizable so you can't write more than the size of the byte array you initialise them with.

If your intention was to write to a file, refer to How to Write to a file using StreamWriter?

Community
  • 1
  • 1
Martin Ullrich
  • 94,744
  • 25
  • 252
  • 217
1

If you create a MemoryStream over a pre-allocated byte array, it can't expand (ie. get longer than the size you specified when you started)

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

you are pre-allocating a buffer of 11 bytes and not the length of the file so when you try to read a string upper than 11 bytes you will get an error

if you need to get the length of the file you should use FileInfo.Length

BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47