我正在尝试使用 C# WebClient 方法 DownloadString() 下载文件,但每次都会引发异常。
每次尝试都会导致此异常:“底层连接已关闭:发送时发生意外错误。” 内部异常是:“身份验证失败,因为远程方已关闭传输流。”
但是,如果我在浏览器中输入这些 URL,它们就可以完美运行。任何想法为什么 DownloadString() 失败?
编码:
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();
}
}