简体   繁体   中英

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? At present I am using WebClient to download file. I am getting the mime type and using that I am mapping it to extensions.

Here this is a custom webclient which depending on HeadOnly property either return the data or just header.

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. This isn't guaranteed to be set though, so if you need to download the file anyways then mime-type is your best bet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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