views:

2056

answers:

4

Hi,
I'm getting an "Illegal characters in path error" while using XMLTextReader method. Basically, I'm sending a long URL to tr.im, and tr.im sends the response as an XML stream, which I'm trying to parse but I get the above mentioned error. Can you guys guide me as to why I'm getting this error and where I'm going wrong? Here's the code:

WebRequest wrURL;
Stream objStream;
string strURL;
wrURL = WebRequest.Create("http://api.tr.im/api/trim_url.xml?url=" + HttpUtility.UrlEncode(txtURL.Text));
objStream = wrURL.GetResponse().GetResponseStream();
StreamReader objSReader = new StreamReader(objStream);
strURL = objSReader.ReadToEnd().ToString();
XmlTextReader reader = new XmlTextReader(strURL); //getting the error at this point

I'm using Visual Studio 2008, Express Edition

+6  A: 

The reason why is you are using the constructor of XmlTextReader which takes a file path as the parameter but you're passing XML content instead.

Try the following code

XmlTextReader reader = new XmlTextReader(new StringReader(strURL));
JaredPar
Amazing. Thanks, your suggestion did not result in the error.
Sathya
A: 

You should print or otherwise display strUrl. Once you can actually see the path that you're passing to the test reader, it should be obvious what the path error is.

Also, just looking at the code, it seems like the response itself might be XML, in which case you should pass objSReader directly to the XmlTextReader constructor.

JSBangs
The response is XML data, as mentioned in the Question. Even with just passing objSReader I was getting the error.
Sathya
+2  A: 

The XmlTextReader(string) constructor expects a file path, not the actual XML data.

You can create an XML reader directly from the stream. The recommended way to do this is using the XmlReader.Create method:

XmlReader reader = XmlReader.Create(objStream);
dtb
getting Error: 'System.Xml.XmlReader.Create(string)' is a 'method' but is used like a 'type' with this.
Sathya
Edited to take out "new", which was the problem.
JSBangs
Yup- works as well.
Sathya
+3  A: 

XmlTextReader constructor accepts a string that points to the URL where an XML file is stored. You are passing it the XML itself which of course is an invalid path. Try this instead:

using (var client = new WebClient())
{
    var xml = client.DownloadString("http://api.tr.im/api/trim_url.xml?url=" + HttpUtility.UrlEncode(txtURL.Text));
    using (var strReader = new StringReader(xml))
    using (var reader = XmlReader.Create(strReader))
    {

    }
}
Darin Dimitrov