0

When I download a file using WebClient. It Downloaded the first time but timeout exception happening on the second download.

The File name is in the Header as contentDisposition It took by using webClient.OpenRead(filePath); then save with this name. Below shown the using code

using (WebClient webClient = new WebClient())
{
    try
    {
        webClient.OpenRead(filePath);
        string cpString = webClient.ResponseHeaders["Content-Disposition"];
        ContentDisposition contentDisposition = new ContentDisposition(cpString);
        string filename = contentDisposition.FileName;
        localPath = Path.Combine(fullpath, filename);
        if (File.Exists(localPath))
        {
            int count = 1;

            string fileNameOnly = Path.GetFileNameWithoutExtension(localPath);
            string extension = Path.GetExtension(localPath);
            string path = Path.GetDirectoryName(localPath);
            string newlocalPath = localPath;

            while (File.Exists(newFullPath))
            {
                string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
                newlocalPath= Path.Combine(path, tempFileName + extension);
            }
           webClient.DownloadFile(filePath, newlocalPath);
        }
        else webClient.DownloadFile(filePath, localPath);
    }
    catch (Exception)
    {
        throw;
    }
    finally
    {
        if (webClient != null)
        {
            webClient.Dispose();
        }
    }
}

Is it a proper way? I would appreciate it if you suggest a solution for this.

slawekwin
  • 6,270
  • 1
  • 44
  • 57
Sanjeev S
  • 626
  • 1
  • 8
  • 27
  • 2
    you don't need the `webClient.Dispose();` in `finally` - that's what `using` does for you – slawekwin Oct 04 '16 at 06:41
  • Try setting timeout manually. Also you should consider asynchronous call since you intend to download multiple files. Check this http://stackoverflow.com/questions/601861/set-timeout-for-webclient-downloadfile – derloopkat Oct 04 '16 at 06:42

0 Answers0