3

I'm trying to download an image from a URL. The URL has a security key appended to the end and I keep getting the following error: System.Net.WebException: An exception occurred during a WebClient request. ---> System.ArgumentException: Illegal characters in path

I'm not sure the correct syntax to use for this. Here is my code below.

string remoteImgPath = "https://mysource.com/2012-08-01/Images/front/y/123456789.jpg?api_key=RgTYUSXe7783u45sRR";
string fileName = Path.GetFileName(remoteImgPath);
string localPath = AppDomain.CurrentDomain.BaseDirectory + "LocalFolder\\Images\\Originals\\" + fileName;
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteImgPath, localPath);
return localPath;
4
  • 1
    I don't think Path.GetFileName does what you think it does. Commented Jan 18, 2012 at 19:37
  • it returns the file name and extension of the specified path string Ah, I wasn't even looking there. I need to split the file so it's not grabbing the query string in the local file path. Commented Jan 18, 2012 at 19:39
  • Brian, that was it. Man, I had when you miss something so obvious. You want to put your answer and I'll mark it? Commented Jan 18, 2012 at 19:45
  • I just added an answer for you... Commented Jan 18, 2012 at 19:46

1 Answer 1

8

I think that this is what you're looking for:

string remoteImgPath = "https://mysource.com/2012-08-01/Images/front/y/123456789.jpg?api_key=RgTYUSXe7783u45sRR";
Uri remoteImgPathUri = new Uri(remoteImgPath);
string remoteImgPathWithoutQuery = remoteImgPathUri.GetLeftPart(UriPartial.Path);
string fileName = Path.GetFileName(remoteImgPathWithoutQuery);
string localPath = AppDomain.CurrentDomain.BaseDirectory + "LocalFolder\\Images\\Originals\\" + fileName;
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteImgPath, localPath);
return localPath;
Sign up to request clarification or add additional context in comments.

1 Comment

In my case, I am getting exception saying "The given path's format is not supported.". What to do ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.