How to download a file from a URL in C#?

前端 未结 11 1106
清歌不尽
清歌不尽 2020-11-22 15:13

What is a simple way of downloading a file from a URL path?

相关标签:
11条回答
  • 2020-11-22 15:20
    using System.Net;
    
    WebClient webClient = new WebClient();
    webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");
    
    0 讨论(0)
  • 2020-11-22 15:27

    As per my research I found that WebClient.DownloadFileAsync is the best way to download file. It is available in System.Net namespace and it supports .net core as well.

    Here is the sample code to download the file.

    using System;
    using System.IO;
    using System.Net;
    using System.ComponentModel;
    
    public class Program
    {
        public static void Main()
        {
            new Program().Download("ftp://localhost/test.zip");
        }
        public void Download(string remoteUri)
        {
            string FilePath = Directory.GetCurrentDirectory() + "/tepdownload/" + Path.GetFileName(remoteUri); // path where download file to be saved, with filename, here I have taken file name from supplied remote url
            using (WebClient client = new WebClient())
            {
                try
                {
                    if (!Directory.Exists("tepdownload"))
                    {
                        Directory.CreateDirectory("tepdownload");
                    }
                    Uri uri = new Uri(remoteUri);
                    //password username of your file server eg. ftp username and password
                    client.Credentials = new NetworkCredential("username", "password");
                    //delegate method, which will be called after file download has been complete.
                    client.DownloadFileCompleted += new AsyncCompletedEventHandler(Extract);
                    //delegate method for progress notification handler.
                    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgessChanged);
                    // uri is the remote url where filed needs to be downloaded, and FilePath is the location where file to be saved
                    client.DownloadFileAsync(uri, FilePath);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        public void Extract(object sender, AsyncCompletedEventArgs e)
        {
            Console.WriteLine("File has been downloaded.");
        }
        public void ProgessChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Console.WriteLine($"Download status: {e.ProgressPercentage}%.");
        }
    }
    

    With above code file will be downloaded inside tepdownload folder of the project's directory. Please read comment in code to understand what above code do.

    0 讨论(0)
  • 2020-11-22 15:30

    Also you can use DownloadFileAsync method in WebClient class. It downloads to a local file the resource with the specified URI. Also this method does not block the calling thread.

    Sample:

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

    For more information:

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

    0 讨论(0)
  • 2020-11-22 15:32

    Try using this:

    private void downloadFile(string url)
    {
         string file = System.IO.Path.GetFileName(url);
         WebClient cln = new WebClient();
         cln.DownloadFile(url, file);
    }
    
    0 讨论(0)
  • 2020-11-22 15:33
    using (var client = new WebClient())
    {
        client.DownloadFile("http://example.com/file/song/a.mpeg", "a.mpeg");
    }
    
    0 讨论(0)
  • 2020-11-22 15:33

    Use System.Net.WebClient.DownloadFile:

    string remoteUri = "http://www.contoso.com/library/homepage/images/";
    string fileName = "ms-banner.gif", myStringWebResource = null;
    
    // Create a new WebClient instance.
    using (WebClient myWebClient = new WebClient())
    {
        myStringWebResource = remoteUri + fileName;
        // Download the Web resource and save it into the current filesystem folder.
        myWebClient.DownloadFile(myStringWebResource, fileName);        
    }
    
    0 讨论(0)
提交回复
热议问题