Search code examples
c#system.netsystem.net.webexception

Error when downloading the file C#


My code:

string dir = "/Users/valeria/Desktop/screening/"+cell;
string remoteUri ="http://www.broadinstitute.org%2Fcmap%2FviewScan.jsp%3Ftype%3DCEL%26scan%3D"+p;
            string pFileName = dir + "/p";

            using (WebClient myWebClient = new WebClient())
            {
                myWebClient.DownloadFile(remoteUri, pFileName);

            }

My program creates a file pFileName, but doesn't download anything because I get the following exception:

Unhandled Exception: System.Net.WebException: Could not find a part of the path "/Users/valeria/Projects/screening/screening/bin/Debug/http:/www.broadinstitute.org/cmap/viewScan.jsp?type=CEL&scan=EC2003090503AA". ---> System.IO.DirectoryNotFoundException: Could not find a part of the path "/Users/valeria/Projects/screening/screening/bin/Debug/http:/www.broadinstitute.org/cmap/viewScan.jsp?type=CEL&scan=EC2003090503AA"

What's wrong?


Solution

  • The escaped URI certainly isn't helping. URL-encoding is generally only used when the item you are encoding is being appended to a URL; encoding the URL itself is unnecessary and can lead to other problems.

    I would strongly suggest changing

      string remoteUri="http://www.broadinstitute.org%2Fcmap%2FviewScan.jsp%3Ftype%3DCEL%26scan%3D"+p;
    

    to

      string remoteUri ="http://www.broadinstitute.org/cmap/viewScan.jsp?type=CEL&scan="+p;
    

    and re-trying.