正在下载的文件的文件大小太大

时间:2019-01-16 12:35:24

标签: c# download webclient

我使用以下代码下载excel文件,它可以工作,但是下载的文件太大。

using (var wc2 = new WebClient())
{
    ServicePointManager.Expect100Continue = true;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

    wc2.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
    // 
    //wc2.DownloadFileAsync(fileUri, AppDomain.CurrentDomain.BaseDirectory + "\\demo\\" + fileName);

    wc2.DownloadFile("https://ds.postnord.com/v2/ptm/file/download/5184.22306", AppDomain.CurrentDomain.BaseDirectory + "\\demo\\test.xls");
}

如果我使用浏览器下载文件,则可以正常运行,但不能使用上述代码。但是,如果我尝试使用上述代码从某处下载jpg文件,则可以正常工作。这里可能有什么问题呢?

1 个答案:

答案 0 :(得分:0)

如果使用WebClient下载的Excel文件已损坏:

您应该添加User-Agent标头,接受标头并使用接受编码。

此外,需要授权;否则,下载的文件将是只读的。

以下代码将下载您的excel文件,而不会损坏或出现任何其他问题:

string Url = "https://ds.postnord.com/v2/ptm/file/download/5184.22306";
string accessToken = "" ;
WebClient c = new WebClient();

c.Headers.Add("Accept: text/html, application/xhtml+xml, application/pdf, */*");
c.Headers.Add("User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
c.Headers.Add("Accept-Encoding: gzip, deflate, br");
c.Headers["Authorization"] = accessToken;

c.DownloadFile(Url, @"c:\\downloaded6.xlsx");