I'm trying to download files using the C# WebClient method DownloadString(), but it throws an exception every time.
Every attempt is causing this exception: "The underlying connection was closed: An unexpected error occurred on a send." The inner exception is: "Authentication failed because the remote party has closed the transport stream."
But these URLs work perfectly if I enter them in a browser. Any ideas why DownloadString() is failing?
The code:
class Program
{
// URI pattern: https://www.nndc.bnl.gov/nudat2/decaysearchdirect.jsp?nuc=235U&unc=nds
static string baseUri = "https://www.nndc.bnl.gov/nudat2/decaysearchdirect.jsp?nuc=";
static string destFolder = @".\Downloaded Files\";
// Create a new WebClient instance.
static WebClient myWebClient = new WebClient();
static XElement isotopes = XElement.Load(@"..\..\..\..\MakeDecayChainLinks\MakeDecayChainLinks\bin\Debug\isotopes2.xml");
static StreamWriter sr = new StreamWriter("Log.rtf");
static void Main(string[] args)
{
foreach (XElement e in isotopes.Elements().Reverse())
{
string isotopeName = e.Attribute("AtomicWeight").Value + e.Attribute("Symbol").Value.ToUpper();
string uri = baseUri + isotopeName + "&unc=nds";
string destFile = destFolder + isotopeName + ".txt";
try
{
string content = myWebClient.DownloadString(uri); // <=== THIS IS WHERE IT FAILS.
using (StreamWriter sw = new StreamWriter(destFile))
sw.Write(content);
sr.WriteLine(isotopeName + " downloaded\nURI: " + uri);
}
catch (Exception ex)
{
sr.WriteLine(isotopeName + " NOT FOUND: " + ex.Message + "\nURI: " + uri);
};
Console.WriteLine(uri);
}
sr.Close();
Console.ReadKey();
}
}