JustBrowsing
JustBrowsing

Reputation: 155

Retrieve the stream file name from a XmlTextReader

This is somewhat trivial but here goes. I am passing an XmlTextReader object to a method using .Net 4.0 framework.

public void TestMethod(XmlTextReader reader)
{
    try
    {
        //...
        //Logic
        //...
    }
    catch(Exception ex)
    {
        //I also want to log the file location of the XmlTextReader!
        Log(ex.Message);
    }
}

If something happens to the reader I want to log where the file the XmlTextReader is reading from. Is there an easy way to get back to the stream the XmlTextReader is using? The reason it is somewhat trivial is that I could easily pass in an additional string to the method containing the file location used to create the stream, but it just seems that has to be a way using only the XmlTextReader.

Thanks!

Update, this is actually what I'm doing... Sorry for the bad example:

public void TestMethod(XmlTextReader reader)
{
        //...
        //Logic
        //...

    if(something_inside_the_XML)
    throw new Exception(FileLocation);
}

Upvotes: 1

Views: 2079

Answers (3)

neural5torm
neural5torm

Reputation: 783

How about this?

reader.BaseUri

This should return the original Uri used when creating your XmlTextReader object.

As the MSDN states:

The base URI tells you where these nodes came from. If there is no base URI for the nodes being returned (for example, they were parsed from an in-memory string), String.Empty is returned.

Upvotes: 3

Bek Raupov
Bek Raupov

Reputation: 3777

XmlTextReader is disposable object, why not change the method signature so that it accepts the filepath and then you can stream read it via XmlTextReader. That will make you cleanly dispose the reader if any errors and log it at the same time

try
{
   using(var reader = new XmlTextReader(filepath) 
   {

   }
}
catch(Exception e)
{
  //Log here
}

Upvotes: 0

QrystaL
QrystaL

Reputation: 4966

Maybe you could use

XmlTextReader.LineNumber
XmlTextReader.LinePosition

Upvotes: 0

Related Questions