I have an application written in C# that pulls daily exchange rates from the national bank website. It's been working fine for months now, only in the last couple of days it fails with the exception (from the topic): Unable to read data from the transport connection: The connection was closed.
Here's the relevant portion of the code that I've been using so far:
|
Now I've noticed that they altered the settings somehow on the server, in that if you access the url from a browser, it doesn't recognize the XML mime type anymore and it prompts you to download the file (it would open it directly in the browser before that).
I've tried to get around that using various methods, here's a sample below:
|
The code above will fail with the mentioned exception just before it reads the last line. Somehow it gets messed up when it hits the end of the stream.
Same happens if I use StreamReader.ReadToEnd() or WebClient.DownloadString().
Anyone got an idea where I got it wrong ?
Alex GaliePosted Jun 12, 2009, 1:59 PM
Yes, that's a working little hack but I was wondering on how to download attachments over HTTP. WebClient.DownloadFile() for example will work only if the web server recognizes the mime type of the requested page, but will fail with the mentioned exception if it doesn't and serves the file as an attachment (like when you get prompted to download a file in the browser).
AdrianPosted Jun 12, 2009, 7:32 AM
private string DownloadBnr()
{
string xml = string.Empty;
WebClient c = new WebClient();
Stream s = c.OpenRead("http://www.bnr.ro/nbrfxrates.xml");
try
{
int n, bloc = 64;
byte[] bytes = new byte[bloc];
do
{
n = s.Read(bytes, 0, bloc);
// The end of the file is reached.
if (n == 0)
break; //Normal condition, never reached at BNR
xml += Encoding.UTF8.GetString(bytes, 0, n);
} while (!xml.EndsWith("")); //Stupid, but working
}
finally
{
s.Close();
}
return xml;
}