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 (将#修改为@)