2
Answers

Unable to read data from the transport connection: The connection was closed.

Photo of Alex  Galie

Alex Galie

15y
13.8k
1
Hi,

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:

XElement ex = XElement.Load("http://www.bnr.ro/nbrfxrates.xml");
var node = (from n in ex.Descendants()
where n.Name.LocalName.ToUpper() == "CUBE"
select n).FirstOrDefault();


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:

WebClient wc = new WebClient();
Stream st = wc.OpenRead("http://www.bnr.ro/nbrfxrates.xml");
StreamReader readStream = new StreamReader(st);

while (!readStream.EndOfStream)
{
sb.Append(readStream.ReadLine());
}

st.Close();


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 ?

Answers (2)

0
Photo of Alex  Galie
NA 3 0 15y
Thanks for the reply.

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).
0
Photo of Adrian
NA 2 0 15y

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("</DataSet>")); //Stupid, but working
}
finally
{
s.Close();
}
return xml;
}