使用windows从服务器下载文件

本文关键字:下载 文件 服务器 windows 使用 | 更新日期: 2023-09-27 18:07:15

我在服务器上有一个大小为164 MB的exe文件,用于安装sccm包。我正在尝试使用WebClientAsync方法将此文件下载到客户端机器。

文件大部分时间处于部分下载状态。因此安装失败。添加下面的代码

PS:

hostpath="https://naagentswhk.cognizant.com/US_IBCM_InstallerV1.exe"
filepath="D:'Users'417193'AppData'Local'SupportSoft'expertouchent'417193'exec"

代码:

private static Boolean  DownloadFile(string HostPath,string Filepath)
{
    WebClient webClient = new WebClient();
    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
    // webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Downloader_DownloadProgressChanged);
    webClient.DownloadFileAsync(new Uri(HostPath), Filepath);
    return true;
}

是否与Async功能有关?

使用windows从服务器下载文件

下载一个文件,我使用这个代码,它为我工作

    private void button1_Click(object sender, EventArgs e)
    {
        WebClient webClient = new WebClient();
        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
        webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
        webClient.DownloadFileAsync(new Uri("https://naagentswhk.cognizant.com/US_IBCM_InstallerV1.exe"), @"D:'Users'417193'AppData'Local'SupportSoft'expertouchent'417193'exec'US_IBCM_InstallerV1.exe");
    }
    private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
    }
    private void Completed(object sender, AsyncCompletedEventArgs e)
    {
        MessageBox.Show("Download completed!");
    }

看看何时以及如何使用async await

private static async Task DownloadFile(string HostPath,string Filepath)
{
    WebClient webClient = new WebClient();

    await webClient.DownloadFileAsync(new Uri(HostPath), Filepath);
}
// usage
private async void SomeMethod(){
   await DownloadFile("url", "path local');
   // it's ready for use. 
   ReadFile("path local)// File is already downloaded at this point
}