从URL路径下载文件的简单方法是什么?


当前回答

在.NET Core MVC中,你有时可以简单地这样做:

public async Task<ActionResult> DownloadUrl(string url) {
    return Redirect(url);
}

这可能假设您正在尝试下载的MIME类型被浏览器设置为可下载(例如.mp4),因此它不会尝试重定向到网页。

其他回答

下面的代码包含下载文件的逻辑与原始名称

private string DownloadFile(string url)
    {

        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        string filename = "";
        string destinationpath = Environment;
        if (!Directory.Exists(destinationpath))
        {
            Directory.CreateDirectory(destinationpath);
        }
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result)
        {
            string path = response.Headers["Content-Disposition"];
            if (string.IsNullOrWhiteSpace(path))
            {
                var uri = new Uri(url);
                filename = Path.GetFileName(uri.LocalPath);
            }
            else
            {
                ContentDisposition contentDisposition = new ContentDisposition(path);
                filename = contentDisposition.FileName;

            }

            var responseStream = response.GetResponseStream();
            using (var fileStream = File.Create(System.IO.Path.Combine(destinationpath, filename)))
            {
                responseStream.CopyTo(fileStream);
            }
        }

        return Path.Combine(destinationpath, filename);
    }

你也可以在WebClient类中使用DownloadFileAsync方法。它将具有指定URI的资源下载到本地文件。此外,此方法不会阻塞调用线程。

示例:

    webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");

欲了解更多信息:

http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/

试试这个:

private void downloadFile(string url)
{
     string file = System.IO.Path.GetFileName(url);
     WebClient cln = new WebClient();
     cln.DownloadFile(url, file);
}

这是我的解决方案,效果很好:

public static void DownloadFile(string url, string pathToSaveFile)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            // or: ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

            using (WebDownload client = new WebDownload())
            {
                client.Headers["User-Agent"] = "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
                client.DownloadFile(new Uri(url), pathToSaveFile);
            }
        }
    
    public class WebDownload : WebClient
        {
            protected override WebRequest GetWebRequest(Uri address)
            {
                HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
                if (request != null)
                {
                    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                }
                return request;
            }
        }

使用GetIsNetworkAvailable()检查网络连接,以避免在未连接到网络时创建空文件。

if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
    using (System.Net.WebClient client = new System.Net.WebClient())
    {                        
          client.DownloadFileAsync(new Uri("http://www.examplesite.com/test.txt"),
          "D:\\test.txt");
    }                  
}