1

I'm trying to download file from URL using WebClient, the problem is that the function .DownloadFile() requiring URL, and name that will be given to the saved file, but when we access to the URL it already has the file name.

How can I keep the file name as it is in the URL?

2
  • 1
    Can you post your current download code? Commented Aug 3, 2014 at 13:04
  • @HenkHolterman: instead of providing numerous options, or just a general answer, a concrete example might help. Commented Aug 3, 2014 at 13:12

3 Answers 3

3

This should work if I understand your question correctly:

private string GetFileNameFromUrl(string url)
{
    if(string.IsNullOrEmpty(url))
        return "image.jpg"; //or throw an ArgumentException

    int sepIndex = url.LastIndexOf("/");

    if(sepIndex == -1)
        return "image.jpg"; //or throw an ArgumentException

    return url.Substring(sepIndex);
}

Then you can use it like so:

string uri = "http://www.mywebsite.com/res/myimage.jpg";
WebClient client = new WebClient();
client.DownloadFile(uri, this.GetFileNameFromUrl(uri));

If you have no control over the url itself you might want to do some validation on it e.g. Regex.

Sign up to request clarification or add additional context in comments.

1 Comment

Basically. Some sanitizing/processing might be advisable.
0

Instead of parsing the url I suggest using function Path.GetFileName():

string uri = "http://yourserveraddress/fileName.txt";
string fileName = System.IO.Path.GetFileName(uri);
WebClient client = new WebClient();
client.DownloadFile(uri, fileName);

Comments

0

What about:

string url = "http://www.mywebsite.com/res/myimage.jpg?guid=2564";
Uri uri = new Uri(url);
string fileName = uri.Segments.Last();

Note: Last() is the extension method from Linq.

Comments

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.