Generic error in GDI+ saving Datagridview data with images to XML

First off - thanks for all the information and snippets around here. Appreciate it. My problem;

I'm trying to save some datagridview data, including images, to an XML file. Then trying to read it back in the grid again. I'm using a dataset & table (unbounded) for easy XML writing as as far as I'm aware - binding doesnt work with an imagecolumn.

I can save the data, then read it in again. However - when I try to save the data again - it fails on the following line in "Sub Savetofile":

For i = 0 To rows
For j = 1 To cols
If j = 1 Then
MyByte = Decompress(DataSet1.Observations.Rows(i).Item(1))
Dim stream As New MemoryStream(MyByte)
DataGridView1.Rows.Add(Image.FromStream(stream))
stream.Close()
ElseIf j >= 2 And DataSet1.Observations.Rows(i).Item(j) IsNot Nothing Then
DataGridView1.Rows(i).Cells(j - 1).Value = DataSet1.Observations.Rows(i).Item(j).ToString
End If
Next
Next

That error is a catch-all which includes anything from file access denied to running out of resources. In this case it is because you are reusing the same MemoryStream over and over.

But you do not have to manually convert the image and "compress" them. If the DataTable has a Byte() column, the DataGridView will know how to convert that for use as an Image. The WriteXML method will also automatically encode the bytes as a Base64 string (and read it back).

XmlWriteMode.WriteSchema is very important. When you read back the data, you want the destination DataTable to know to convert that Base64 string back to a Byte array rather than displaying iVBORw0KGgoAAAANSUhEUgAAABA...

Also note the Using block. This will dispose of the MemoryStream at the end and allow it to free any resources it allocates. This is missing in your code and as a result the MemoryStream is accumulating data in addition to leaking:

If I use the same one on very small images, the size of the stream reports 334, 684, 1014, 1361.... It is accumulating image data and all but the first image will be corrupt resulting in the GDI error.