Download Files using C# from https Website

Rav*_*avi 0 c# https webclient

我正在尝试从 https 网站下载 pdf 文件,但它不起作用。我是 C# 新手,所以做了一些研究并找到了一个简单的代码。更糟糕的是,我得到的异常非常普遍。请帮助。

    static void Main(string[] args)
    {

        string file_ = "https://www.nseindia.com/content/circulars/CMPT34469.pdf";
        string path_ = @"E:\RSR\Office\EEP\FileDownloader\output\Hello_World.pdf";

        WebClient wc_ = new WebClient();
        wc_.DownloadFile(file_, path_);
    }
Run Code Online (Sandbox Code Playgroud)

异常:System.dll 中发生类型为“System.Net.WebException”的未处理异常附加信息:远程服务器返回错误:(403) 禁止。

Joh*_*ica 5

服务器正在使用用户代理标头检查您是否是真实用户。它还要求您指定所需的 mime 类型。这不是一般的C# 事物,它只是您要连接的主机 (nseindia.com)。

这对我有用。

static void Main(string[] args)
{

    string file_ = "https://www.nseindia.com/content/circulars/CMPT34469.pdf";
    string path_ = @"E:\RSR\Office\EEP\FileDownloader\output\Hello_World.pdf";

    WebClient wc_ = new WebClient();
    wc_.Headers.Add(HttpRequestHeader.UserAgent, "Other");
    wc_.Headers.Add(HttpRequestHeader.Accept, "application/pdf");
    wc_.DownloadFile(file_, path_);
}
Run Code Online (Sandbox Code Playgroud)