-1

I have an XmlTextReader, and I pass it in a System.Net.ConnectStream. If I enter the debugger, I can see that ConnectStream does not support the Length property and this throws a NotSupportedException.

Now, I subclass Stream and pass in an instance of my class. My class also throws NotSupportedException on the get() accessor of Length, but this time all my unit tests fail with a NotSupportedException.

The XmlTextReader documentation does not say it requires a Stream supporting Length, and it clearly can use one that doesn't - what is going on?

(This is .NET 3.5 Client)

sebf
  • 2,831
  • 5
  • 32
  • 50
  • 4
    What does your `Stream.CanSeek` return? It would be helpful if you could provide a short but complete program demonstrating the problem. – Jon Skeet Oct 29 '15 at 19:36
  • 1
    Have you tried XmlDocument. Super easy to use if you're not using big chunks of XML. – Mr. B Oct 29 '15 at 19:44
  • @JonSkeet - My Stream returned CanSeek as true (which it can, in the data it already has - it just doesn't know how much data it may recieve) unlike ConnectStream. If I change this to false, XmlTextReader works fine. Thanks for the pointer! If you add that as an answer I'll accept it. – sebf Oct 29 '15 at 20:10
  • @Mr.B I am actually using XmlSerialiser, passing in an XmlTextReader (in order to use the Deserialise() method) but thanks for the heads up about XmlDocument, I'll keep that in mind for future applications. – sebf Oct 29 '15 at 20:12
  • @Mr.B: It's not *nearly* as easy to use as LINQ to XML, IMO. I would take XDocument over XmlDocument any day of the week - particularly if namespaces are involved. – Jon Skeet Oct 29 '15 at 20:28
  • @JonSkeet Yep you're right. – Mr. B Oct 30 '15 at 02:24

1 Answers1

2

If a Stream returns true from CanSeek, it assumed that Length, SetLength, Position and Seek are all supported. Some code may test CanSeek and use the result to optimize its behaviour - as seems to be the case here. When you return true from CanSeek but then throw an exception in Length, that's breaking the not-terribly-well-documented contract of Stream.

If you can't support the Length property, it's best to return false from CanSeek.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194