In .net 4 and C #. I applied a static method to deserialize an XML stream into an object. This is only one XML format that goes into one object, so I am not trying to do anything with this. Since I can get this XML content in various ways, I decided that I passed the parameter to the static method of the Stream object. I thought that then it would take any object obtained from the Stream base class - like FileStream, MemoryStream, StringReader, etc.
It works fine when I pass it a FileStream object, but not when I pass it a StringReader.
My static method:
public static MatchObj DeserializeMatch(Stream srXml) { XmlSerializer xs = new XmlSerializer(typeof(MatchObj)); MatchObj mObj = (MatchObj)xs.Deserialize(srXml); return mObj; }
It works with FileStream:
MatchObj objReply; using (FileStream fs = new FileStream(Server.MapPath("/App_Data/Match.xml"), FileMode.Open)) { objReply = MStatic.DeserializeMatch(fs); fs.Close(); }
But not StringReader:
StringReader sr = new StringReader(Request.Form["mXML"]); MatchObj objReply = MStatic.DeserializeMatch(sr);
Build error: "cannot convert from" System.IO.StringReader "to" System.IO.Stream "
Which in itself makes sense, but I thought that since StringReader implements TextReader, is it considered Stream? XML Deserializer works great with any of them.
I worked on it simply by overloading this method to take a StringReader, but I don't like to see that I thought the elegant idea was falling apart. Any ideas on why this is not working, and / or a way to make it work?
source share