Miki Shah Miki Shah - 1 month ago 9
ASP.NET (C#) Question

How to get FileName from url

I have url like


and need to get only filename from url like "

url format is dynamic. Filename with extension must be in url. but it filename with extension may not be in last position of url

I have tried Path.GetFileName() but it give "".

is anyone know how extract filename for this type of url?


12-8536_2.jpg does not seem to be a file in that URL. In any case, if the "filename" in the URL will always be in .jpg, you can output the URL to a string (or AS a string) and Regex for it:

string filename = Regex.Match(URL,@"\/([A-Za-z0-9\-._~:?#\[\]@!$%&'()*+,;=]*).jpg").Groups[1].Value

EDIT: I'm thinking this is for a site with different preview sizes for a specific file. You can also specify the different possible extensions as follows (for example):

string filename = Regex.Match(URL,@"\/([A-Za-z0-9\-._~:?#\[\]@!$%&'()*+,;=]*)(.jpg|.JPG|.jpeg|.JPEG)").Groups[1].Value