I'm sure I missed something simple but I'm getting frustrated with this code simply because I'm so sure it should work.

I have created a short program for exporting some XML data was use at the office into .tsv files. I have a thread dedicated to reading the xml data from a file (and a writer thread then writes the data to an outside file). My problem is that my reader opens an XML file, parses through the entire file, then causes the close() method. The writer then finishes up writing and the program returns to the main form. The problem is if I choose to parse the same XML file again then the xmlreader starts reading at the position I left off from (in this case the end of the file). Thus the writer and reader do no work and I get a tsv file with only the column headers, but no data.


My question is, what did I do wrong? I'm sure I just missed something simple.

private void readXMLData()
        {
            //Connect to the xml file.
            //xmlreader = new XmlTextReader(inputFilePath);
            XmlReaderSettings xmlreaderSettings = new XmlReaderSettings();
            xmlreaderSettings.CloseInput = true;
            xmlreaderSettings.ProhibitDtd = false;

            xmlreader = XmlReader.Create(inputFilePath, xmlreaderSettings);
            

            //Continue to do work as long as there is stuff to read off of the xmlreader.
            while (xmlreader.Read())
            {
             //Parsing code...
            }

            xmlreader.Close();

            GC.Collect();
        }

Any help would be greatly appreciated.

After messing with it a bit more I think I solved it. For whatever reason it seems the xmlreader didn't want to close it despite the fact that I turned close input on.

So instead I used a TextReader to open the file for reading, then passed the TextReader to the XMLReader. Once I closed the XMLReader I called Close and Dispose on the reader and it seems to get everything reset.

Fixed code below in case someone else encounters a similar oddity.

private void readXMLData()
        {
            //Connect to the xml file.
            //xmlreader = new XmlTextReader(inputFilePath);
            XmlReaderSettings xmlreaderSettings = new XmlReaderSettings();
            TextReader txtReader = File.OpenText(inputFilePath);
            xmlreaderSettings.CloseInput = true;
            xmlreaderSettings.ProhibitDtd = false;

            xmlreader = XmlReader.Create(txtReader, xmlreaderSettings);

            while (xmlreader.Read())
            {
             //Parsing and such....
            }

            txtReader.Close();
            txtReader.Dispose();

            xmlreader.Close();

            GC.Collect();
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.