Search code examples
c#webclientresponse-headerswebexception

I get WebException timeout when I use webclient.DownloadFile after webclient.ResponseHeaders


I am trying to create my own download manger. When a link is added to the download manger I use a webclient to get it's information from the server. Like so

WebClient webClient = new WebClient();
webClient.OpenRead(link);
string filename = webClient.ResponseHeaders["Content-Disposition"];

After that I download the file using DownloadFile

FileInfo fileInfo = new FileInfo(path);
if (!fileInfo.Exists)
{
    webClient.DownloadFile(link, path);
}

When I do it like this. I get a WebException timeout. However, when I remove the webClient.ResponseHeaders part. It never get the timeout exception. I really need to read the Content-Disposition because some of the links don't have the name of the file on them. I even tried using a different webclient for downloading and getting it's info but I got the same result.


Solution

  • I was able to fix the problem by finding another way to get the files info.

    string Name = "";
    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(Link);
    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
    
    for(int i=0; i < myHttpWebResponse.Headers.Count; i++)
    {
        if (myHttpWebResponse.Headers.Keys[i] == "Content-Disposition")
        {
            Name = myHttpWebResponse.Headers[i];
        }
    }
    myHttpWebResponse.Close();