C # EndOfStream is always true - Seek / Position to 0 not works

I want to determine the encoding of an XML document before parsing it. So I found this script overflow on the stack .

public static XElement GetXMLFromStream(Stream uploadStream)
{
    /** Remember position */
    var position = uploadStream.Position;

    /** Get encoding */
    var xmlReader = new XmlTextReader(uploadStream);
    xmlReader.MoveToContent();

    /** Move to remembered position */
    uploadStream.Seek(position, SeekOrigin.Begin); // with "pos" = 0 it not works, too
    uploadStream.Seek(position, SeekOrigin.Current); // if I remove this I have the same issue!

    /** Read content with detected encoding */
    var streamReader = new StreamReader(uploadStream, xmlReader.Encoding);
    var streamReaderString = streamReader.ReadToEnd();
    return XElement.Parse(streamReaderString);
}

But that will not work. I always get EndOfStream true . But it is not!!!! -.-

For example, I have a string <test></test>. Start: 0, End: 13

If I ReadToEndor MoveToContent, then the end will succeed. EndOfStream to true .

If I reset the position through Seekor Positionequal to 0 (for example), then a new StreamReaderalways shows EndOfStream true .

The fact is that uploadStreamthis is a thread that I cannot close.

This is the SharpZipLib HTTP stream stream stream. Therefore, I cannot close this thread. I can work with him.

, Position Seek ... , ReadToEnd Position. - . !

, : -)

Advance!

: Example <code> EndOfStream </code> true - but the position is not at the end!

+4
2

. Seek . , Stream , Seek, CanSeek. , Seek .

, MemoryStream. Seek, , . , ReadToEnd(), , , , , , .

: , Seek , NotSupportedException. , , , , . , , , CanSeek false , .

+2

1:

XElement Load(), xml. . , . .

XElement.Load(uploadStream);

2:

, XmlTextReader(). XmlTextReader.Create() , :

var xmlReader = XmlTextReader.Create(uploadStream);
var streamReaderString = xmlReader.ReadOuterXml();
return XElement.Parse(streamReaderString);
+1

All Articles