Miki Shah Miki Shah - 3 months ago 14
ASP.NET (C#) Question

How to get FileName from url

I have url like

http://xxx.xxx.xxx/mls/pmmls/12/-8/53/6/12-8536_2.jpg/t1349940727/100x100/

and need to get only filename from url like "
12-8536_2.jpg"


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?

Answer

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
Comments