shaiws
shaiws

Reputation: 39

How to download file in C# with its name?

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?

Upvotes: 1

Views: 4183

Answers (3)

Axel H
Axel H

Reputation: 11

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.

Upvotes: 0

dotnetom
dotnetom

Reputation: 24901

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);

Upvotes: 0

Jurgen Camilleri
Jurgen Camilleri

Reputation: 3589

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.

Upvotes: 3

Related Questions