Stream was not readable error
52,433
Solution 1
When this block of code completes, it will also dispose the attached MemoryStream
using (StreamWriter sw = new StreamWriter(ms))
{
foreach (Conflict ct in Conflicts)
xmlSerializer.Serialize(sw, ct);
sw.Flush(); //Site tip
ms.Position = 0; //Site tip
}
Remove the using statement, and dispose the stream manually after you are done with it
StreamWriter sw = new StreamWriter(ms);
foreach (Conflict ct in Conflicts)
xmlSerializer.Serialize(sw, ct);
sw.Flush(); //Site tip
ms.Position = 0; //Site tip
// other code that uses MemoryStream here...
sw.Dispose();
Solution 2
Try this instead (assuming Conflicts is of type List<Conflict>
):
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Conflict>));
StringWriter sw = new StringWriter();
xmlSerializer.Serialize(sw, Conflicts);
string conflictXml = sw.GetStringBuilder().ToString();
Related videos on Youtube
Author by
Arnold Krohn
Updated on July 09, 2022Comments
-
Arnold Krohn over 1 year
I am getting the message "Stream was not readable" on the statement:
using (StreamReader sr = new StreamReader(ms))
I have tried the tips posted here without success. Thanks for the help.
This is my code:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Conflict)); //Serialize Conflicts array to memorystream as XML using (MemoryStream ms = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(ms)) { foreach (Conflict ct in Conflicts) xmlSerializer.Serialize(sw, ct); sw.Flush(); //Site tip ms.Position = 0; //Site tip } //Retrieve memory stream to string using (StreamReader sr = new StreamReader(ms)) { string conflictXml = String.Format(CultureInfo.InvariantCulture, "{0}</NewDataSet>",
-
BrMcMullin almost 13 yearsFormatted code would be easier to follow and help debug
-
Lasse V. Karlsen almost 13 yearsStreamWriter and StreamReader both close the underlying stream when disposed of, as such, when you get to trying to read from the stream that was closed when you disposed of the StreamWriter, the stream is no longer open for reading or writing. Unfortunately I am not at my computer now, but other answers on this site has classes for wrapping the underlying stream to prevent it from being closed.
-
-
Arnold Krohn almost 13 yearsWill this only work with a generic collection? I'm stuck right now with .Net 1.1.
-
user3285954 about 8 yearsIn .Net 4.5 there's a StreamWriter overload where can be specified to leave the stream open: msdn.microsoft.com/EN-US/library/gg712853(v=VS.110,d=hv.2).aspx
-
Gabrielius almost 6 yearsAnd don't forget to enclose everything in
try/finally
block and addsw.Dispose()
infinally
block. You will need to defineStreamWriter sw
outsidetry/finally
block.