从给定的URL下载文件

本文关键字:下载 文件 URL | 更新日期: 2023-09-27 18:18:34

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

这是一个自定义的web客户端,这取决于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;
    }
}

从给定的URL下载文件

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

    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;
    }

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