I want to know that for make sure that the file that will be download from my script will have the extension I want.
The file will not be at URLs like:
h
If you just want to get the .jpg
part of http://example.com/file.jpg
then just use Path.GetExtension as heringer suggests.
// The following evaluates to ".jpg"
Path.GetExtension("http://example.com/file.jpg")
If the download link is something like http://example.com/this_url_will_download_a_file
then the filename will be contained as part of the Content-Disposition, a HTTP header that is used to suggest a filename for browsers that display a "save file" dialog. If you want to get this filename then you can use the technique suggested by Get filename without Content-Disposition to initiate the download and get the HTTP headers, but cancel the download without actually downloading any of the file
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
using (Stream rstream = res.GetResponseStream())
{
string fileName = res.Headers["Content-Disposition"] != null ?
res.Headers["Content-Disposition"].Replace("attachment; filename=", "").Replace("\"", "") :
res.Headers["Location"] != null ? Path.GetFileName(res.Headers["Location"]) :
Path.GetFileName(url).Contains('?') || Path.GetFileName(url).Contains('=') ?
Path.GetFileName(res.ResponseUri.ToString()) : defaultFileName;
}
res.Close();