ArgumentException Stream was not readable.
Closed this issue · 4 comments
I have the following example:
public static class XmlSerializerHelper
{
public static void Serialize<T>(this T obj, string destPath)
{
var xmlSerializer = new ConfigurationContainer()
.UseAutoFormatting()
.UseOptimizedNamespaces()
.EnableImplicitTyping(typeof(T))
// Additional configurations...
.Create();
using (var fileStream = new FileStream(destPath, FileMode.Create, FileAccess.Write))
{
xmlSerializer.Serialize(fileStream, obj);
}
}
}
And it throws the follwing error:
System.ArgumentException
HResult=0x80070057
Message=Stream was not readable.
Source=System.Private.CoreLib
StackTrace:
at System.IO.StreamReader..ctor(Stream stream, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean leaveOpen)
at System.IO.StreamReader..ctor(Stream stream)
at ExtendedXmlSerializer.ExtensionModel.Xml.InstanceFormatter.Get(Object parameter)
at ExtendedXmlSerializer.ExtensionMethodsForSerialization.Serialize(IExtendedXmlSerializer this, IXmlWriterFactory factory, Func`1 stream, Object instance)
at ExtendedXmlSerializer.ExtensionMethodsForSerialization.Serialize(IExtendedXmlSerializer this, Stream stream, Object instance)
at ParcelTest.Helpers.XmlSerializerHelper.Serialize[T](T obj, String destPath) in C:\Code\parcel-test\ParcelTest\Helpers\XmlSerializerHelper.cs:line 34
at ParcelTest.Program.Main(String[] args) in C:\Code\parcel-test\ParcelTest\Program.cs:line 16
Any idea why it's happening?
Also I cannot understand why the method returns string
. In case of huge amount of data I thought the stream allows to write all data gradually without increasing memory pool. That is how the original XmlSerializer
works.
Hi @fairking thank you for writing in with your question here. I will see if I can assist.
Any idea why it's happening?
Indeed, it is related to your second concern here:
Also I cannot understand why the method returns string.
You are actually calling a convenience extension method that we use extensively to forego the use of streams. If you would like to use a custom stream, try making use of the XmlWriter.Create
method:
using (var fileStream = new FileStream(destPath, FileMode.Create, FileAccess.Write))
{
using (var writer = XmlWriter.Create(fileStream))
{
xmlSerializer.Serialize(writer, obj);
}
}
That should get you closer to the results/experience that you are looking for... if you do have any further problems let me know and I will see if I get it answered for you. 👍
FWIW @fairking here is the contract the xmlSerializer
variable in the code you provided implements:
Note the use of System.Xml.XmlWriter
and System.Xml.XmlReader
, the same that the traditional XmlSerializer
uses.
A configurable and eXtensible Xml serializer for .NET. - home/ISerializer.cs at master · ExtendedXmlSerializer/home
Looks like this issue was answered, and will close for now. If you do have any further questions please do leave a comment and we can take it from there.