我尝试过使用以下代码。收到的错误是"基础连接已关闭:接收时发生意外错误"。
系统操作系统: 视窗 7 家庭基本 SP1 .net 版本:4.5.2
using System;
using System.Net;
using System.Net.Security;
namespace wc_downloadfile
{
class Program
{
public static void Main(string[] args)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
using(WebClient wc = new WebClient())
{
string src = "https://nseindia.com/content/indices/ind_nifty50list.csv";
string dest = @"C:tempN50.csv";
try
{
var ua = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";
wc.Headers.Add(HttpRequestHeader.UserAgent, ua);
wc.Headers.Add(HttpRequestHeader.Accept, "*/*");
wc.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
wc.DownloadFile(src, dest);
}
catch (Exception e)
{
Console.WriteLine("Unable to download file --- " + e.Message);
}
}
Console.ReadKey(true);
}
}
}
修改了用户代理值,问题已解决。以下是工作代码。
using System;
using System.Net;
using System.Net.Security;
namespace wc_downloadfile
{
class Program
{
public static void Main(string[] args)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
using(WebClient wc = new WebClient())
{
string src = "https://nseindia.com/content/indices/ind_nifty50list.csv";
string dest = @"C:tempN50.csv";
try
{
//Removed Chrome/61.0.3163.100
var ua = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36";
wc.Headers.Add(HttpRequestHeader.UserAgent, ua);
wc.Headers.Add(HttpRequestHeader.Accept, "*/*");
wc.DownloadFile(src, dest);
}
catch (Exception e)
{
Console.WriteLine("Unable to download file --- " + e.Message);
}
}
Console.ReadKey(true);
}
}
}
WebClient client = new WebClient();
client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)");
Stream stream = client.OpenRead("https://nseindia.com/content/indices/ind_nifty50list.csv");
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();