简体   繁体   English

从给定URL下载文件

[英]Download File from Given URL

Can someone tell me a good way of getting the file extension when trying to download file from the given URI? 尝试从给定URI下载文件时,有人可以告诉我一种获取文件扩展名的好方法吗? At present I am using WebClient to download file. 目前,我正在使用WebClient下载文件。 I am getting the mime type and using that I am mapping it to extensions. 我得到的MIME类型,并使用它映射到扩展名。

Here this is a custom webclient which depending on HeadOnly property either return the data or just header. 这是一个自定义的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;
    }
}

This should help...I used it to download the latest update file for clients. 这应该有所帮助...我用它来为客户端下载最新的更新文件。 All you need is a button and a progress bar. 您只需要一个按钮和一个进度条。

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

If you just need the file type and not the file, just look at the last segment of the URI and check that for known file types. 如果您只需要文件类型而不是文件,则只需查看URI的最后一段,然后检查一下已知文件类型即可。 This isn't guaranteed to be set though, so if you need to download the file anyways then mime-type is your best bet. 不过,不能保证设置该值,因此,如果仍然需要下载文件,那么最好选择mime-type。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM