如何解决C# WebClient DownloadString() 抛出异常
我正在尝试使用 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();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。