从给定URL下载文件

时间:2011-12-22 20:13:13

标签: c# download webclient

有人告诉我在尝试从给定URI下载文件时获取文件扩展名的好方法吗? 目前我正在使用WebClient下载文件。 我正在获取mime类型并使用它将其映射到扩展名。

这是一个自定义webclient,它依赖于HeadOnly属性返回数据或只是标题。

public class SlideWebClient : WebClient {
    public bool HeadOnly { get; set; }
        protected override WebRequest GetWebRequest(Uri address) {
            WebRequest req = base.GetWebRequest(address);
            if (HeadOnly && req.Method == "GET") {
                req.Method = "HEAD";
            }
            return req;
        }
    }
}


public class FileDownloader {           

    /// <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 static void DownloadFile(Uri source, string destination) {
        try {
            using (WebClient _WebClient = new WebClient()) {
                // Downloads the resource with the specified URI 
                // to a local file.
                _WebClient.DownloadFile(source, destination);
            }
        } catch (Exception _Exception) {
            // Error
            Console.WriteLine("Exception caught in process: {0}", 
                _Exception.ToString());
        }
    }

    /// <summary>
    ///Get the Content type of file to be downloaded  for given URI
    /// </summary>
    /// <returns></returns>
    public static String GetContentType(Uri url) {
        using (SlideWebClient client = new SlideWebClient()) {
            client.HeadOnly = true;
            // note should be 0-length
            byte[] body = client.DownloadData(url); 
            return client.ResponseHeaders["content-type"];
        }
    }

    public static bool  IsPdf(string contentType) {
        if (contentType.Contains("application/pdf")) return true;
        else return false;
    }
}

2 个答案:

答案 0 :(得分:1)

这应该有帮助...我用它来下载客户端的最新更新文件。您只需要一个按钮和一个进度条。

    private void btnStartDownload_Click(object sender, EventArgs e)
    {
        WebClient client = new WebClient();
        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
        client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);

        client.DownloadFileAsync(new Uri(@"http://www.trendmicro.com/ftp/products/wfbs/WFBS70_EN_GM_B1343.exe"), @"C:\temp\WFBS7.exe");
        btnStartDownload.Text = "Download In Process";
        btnStartDownload.Enabled = false;
    }

    void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        double bytesIn = double.Parse(e.BytesReceived.ToString());
        double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
        double percentage = bytesIn / totalBytes * 100;
        progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
    }

    void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
        MessageBox.Show("Download Completed");
        btnStartDownload.Text = "Start Download";
        btnStartDownload.Enabled = true;
    }

答案 1 :(得分:0)

如果您只需要文件类型而不是文件,只需查看URI的最后一段并检查是否已知文件类型。这不保证设置,所以如果你需要下载文件,那么mime-type是你最好的选择。

相关问题