Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Hey friends,

I want to read through large XML files. To do so, I use a FileStream object and a XmlReader object. I want to know the FileStream's position for every element read by the XmlReader :

C#
using (FileStream strmFile = new FileStream(Some XML File))
{
  using (XmlReader xmlReader = XmlReader.Create(strmFile, settings))
  {
    while (xmlReader.Read())
    {
      switch (xmlReader.NodeType)
      {
        case XmlNodeType.Element:
          // Get the FileStream position here
          break;
      }
    }
  }
}


Because the XmlReader advances through the file using a 8K buffer, the FileStream's Position property returns 8K over and over again until the stream advances to the next 8K.

Is there a way to retrieve the absolute stream position?
Posted
Updated 18-Mar-11 4:27am
v2
Comments
Abdul Quader Mamun 18-Mar-11 10:27am    
Edited spelling.

1 solution

// Get the FileStream position here . The File stream position would be 100%

XmlReader xmlReader = XmlReader.Create(strmFile, settings) will take the entire file stream to its memory.

As proof close the file stream here.

C#
using (XmlReader xmlReader = XmlReader.Create(strmFile, settings))
  {
    strmFile.close();


Your reader can still proceed.

Improved Answer
------------------------
To get Line Number and Line Position

C#
IXmlLineInfo LineInfo;
using (FileStream strmFile = new FileStream("some file name"))
{
     using (XmlReader xmlReader = XmlReader.Create(strmFile))
  {
      LineInfo = (IXmlLineInfo)xmlReader;
    while (xmlReader.Read())
    {
      switch (xmlReader.NodeType)
      {
        case XmlNodeType.Element:
             // Get the FileStream position here
              MessageBox.Show(LineInfo.LineNumber.ToString());
              MessageBox.Show(LineInfo.LinePosition.ToString());
          break;
      }
    }
  }
}
 
Share this answer
 
v3
Comments
Eduard Keilholz 18-Mar-11 10:45am    
OK, let's assume you're right (I haven't tried it yet), but how does this answer my question that I want to know the position of the start element in the source file?
Albin Abel 18-Mar-11 11:51am    
I have given an improved answer about getting Line number and position. In your setting don't remove the white spaces. So it most probably matches with position is the file as well.
Eduard Keilholz 18-Mar-11 12:39pm    
Thanks for your effort, but it doesn;t because in most of the XML files we use, all white space is already removed. Unfortunately line numbers don't work as well...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900