Download File from URL

Đoạn code này sử dụng để down một file trên internet

/// <summary>
/// Function to download a file from URL and save it to local drive
/// </summary>
/// <param name="_URL">URL address to download file</param>
public void DownloadFile(string _URL, string _SaveAs)
        System.Net.WebClient _WebClient = new System.Net.WebClient();
        // Downloads the resource with the specified URI to a local file.
        _WebClient.DownloadFile(_URL, _SaveAs);
    catch (Exception _Exception)
        // Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());

Sử dụng

DownloadFile("", @"C:\");

Sử dụng tiếp tính down load

// Occurs when an asynchronous file download operation completes.
private void _DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    // File download completed
    download_button.Enabled = Enabled;
    MessageBox.Show("Download completed");

// Occurs when an asynchronous download operation successfully transfers some or all of the data.
private void _DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
    // Update progress bar
    progressBar1.Value = e.ProgressPercentage;

// download button click event
private void download_button_Click(object sender, EventArgs e)
    // Disable download button to avoid clicking again while downloading the file
    download_button.Enabled = false;

    // Downloads, to a local file, the resource with the specified URI. 
    // This method does not block the calling thread.
    System.Net.WebClient _WebClient = new System.Net.WebClient();
    _WebClient.DownloadFileCompleted += new AsyncCompletedEventHandler(_DownloadFileCompleted);
    _WebClient.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_DownloadProgressChanged);
    _WebClient.DownloadFileAsync(new Uri(""), @"C:\");