如何从HttpWebResponse

时间:2015-07-07 06:18:13

标签: c#

我有一个方法可以在保留原始名称/扩展名的同时下载文件:

public void downloadFile(string urlAddress, string location)
    {
        _fileHasher = new HashFile(_controlsRef);

        using (var downloadClient = new WebClient())
        {
            downloadClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Completed);
            downloadClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);

            WebRequest request = WebRequest.Create(urlAddress);
            WebResponse response = request.GetResponse();
            string contentDisposition = response.Headers["Content-Disposition"];
            const string contentFileNamePortion = "filename=";
            Int32 fileNameStartIndex = contentDisposition.IndexOf(contentFileNamePortion, StringComparison.InvariantCulture) + contentFileNamePortion.Length;
            Int32 originalFileNameLength = contentDisposition.Length - fileNameStartIndex;
            string originalFileName = contentDisposition.Substring(fileNameStartIndex, originalFileNameLength);

            Uri URL = new Uri(urlAddress);
            location += "\\" + originalFileName;
            this._location = location;
            _downloadStopWatch.Start();
            try
            {
                downloadClient.DownloadFileAsync(URL, location);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }                                  
    }

然后我查找了一个仅在硬盘驱动器上的文件较旧时才下载文件的方法:

public void DownloadAndReplace(FileSystemInfo sourceFile)
    {
        var requestFile = (HttpWebRequest)WebRequest.Create("");
        requestFile.Method = "HEAD";
        var responseFile = (HttpWebResponse)requestFile.GetResponse();

        if (responseFile.LastModified > sourceFile.LastWriteTime)
        {
           // downloadFile(Here's the problem);
        }
    }

我的问题是,如何从DownloadAndReplace方法正确调用downloadFile方法?

1 个答案:

答案 0 :(得分:1)

你试过吗

WebRequest.RequestUri - 在后代类中重写时,获取与请求关联的Internet资源的URI。

HttpWebResponse.ResponseUri