无法下载文件 - 远程服务器返回错误:(403)Forbidden

时间:2017-08-08 12:17:44

标签: c#

我试图在Windows应用程序中下载一个zip文件,但是发生了错误。我的代码是:

    string url = "https://www.nseindia.com/content/historical/DERIVATIVES/2017/JUN/fo07JUN2017bhav.csv.zip";
    using (WebClient wc = new WebClient())
    {
        wc.DownloadFile(url, @"c:\bhav\file.zip");
    }

异常详情:

  

System.Net.WebException未处理HResult = -2146233079
  消息=远程服务器返回错误:(403)禁止   Source = System StackTrace:          在System.Net.WebClient.DownloadFile(Uri地址,字符串fileName)          在System.Net.WebClient.DownloadFile(String address,String fileName)          在c:\ users \ ethicpro \ documents \ visual studio中的unzip.Form1.downloadFile()中   2015 \ Projects \ unzip \ unzip \ Form1.cs:第30行          at c:\ users \ ethicpro \ documents \ visual studio 2015中的unzip.Form1..ctor()\ Projects \ unzip \ unzip \ Form1.cs:第20行          at unzip.Program.Main()在c:\ users \ ethicpro \ documents \ visual studio 2015 \ Projects \ unzip \ unzip \ Program.cs:第19行          在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args)          在System.AppDomain.nExecuteAssembly(RuntimeAssembly程序集,String [] args)          在System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)          在System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()          在System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext   activationContext,String [] activationCustomData)          在System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext   activationContext)          在System.Activator.CreateInstance(ActivationContext activationContext)          在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()          在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)          在System.Threading.ExecutionContext.RunInternal(ExecutionContext   executionContext,ContextCallback回调,对象状态,布尔值   preserveSyncCtx)          at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean   preserveSyncCtx)          在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)          在System.Threading.ThreadHelper.ThreadStart()InnerException:

链接是:https://www.nseindia.com/content/historical/DERIVATIVES/2017/JUN/fo07JUN2017bhav.csv.zip

我搜索了其他问题,但没有得到正确答案。

1 个答案:

答案 0 :(得分:1)

试试这个

string url = "https://www.nseindia.com/content/historical/DERIVATIVES/2017/JUN/fo07JUN2017bhav.csv.zip";
        string fileName = @"C:\Temp\tt.zip";
        using (WebClient wc = new WebClient())
        {
            wc.Headers.Add("User-Agent: Other"); 
            wc.DownloadFile(url, fileName);
    }