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

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

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

11条回答
  •  萌比男神i
    2020-11-22 15:44

    You may need to know the status and update a ProgressBar during the file download or use credentials before making the request.

    Here it is, an example that covers these options. Lambda notation and String interpolation has been used:

    using System.Net;
    // ...
    
    using (WebClient client = new WebClient()) {
        Uri ur = new Uri("http://remotehost.do/images/img.jpg");
    
        //client.Credentials = new NetworkCredential("username", "password");
        String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
        client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
    
        client.DownloadProgressChanged += (o, e) =>
        {
            Console.WriteLine($"Download status: {e.ProgressPercentage}%.");
    
            // updating the UI
            Dispatcher.Invoke(() => {
                progressBar.Value = e.ProgressPercentage;
            });
        };
    
        client.DownloadDataCompleted += (o, e) => 
        {
            Console.WriteLine("Download finished!");
        };
    
        client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
    }
    

提交回复
热议问题