3

Hiee guys,

I have several image urls from which i download the data and save it in db. I use (imageurl.Split('/'))[(imageurl.Split('/').Length) - 1]; to create the filename.

Problem is,there are some urls which contains query string. due to which filenames i get for them have pattern imgname.img_type_extension?somefield=somevalue

How can i get filename.extension leaving query string from above substring??

Thanks for stopping by...

5
  • 1
    Did you try Path.GetFileNameWithoutExtension()? Commented Jun 12, 2013 at 7:43
  • i have my urls coming from database and not from pages Commented Jun 12, 2013 at 7:44
  • I never assume it comes from eleswhere. Commented Jun 12, 2013 at 7:46
  • Do you store the full path of the file in the DB? Commented Jun 12, 2013 at 7:46
  • yes onam.i store fullpath of images in DB Commented Jun 12, 2013 at 7:48

4 Answers 4

5
var path = imageurl.Split('?')[0]; var fileName = Path.GetFileNameWithoutExtension(path); 

EDIT : for file name WITH extension just use another method from Path

 var path = imageurl.Split('?')[0]; var fileName = Path.GetFileName(path); 
Sign up to request clarification or add additional context in comments.

3 Comments

Actually like this one. Didn't know about System.IO.Path.. learn something new everyday!
I was under the impression that you needed file name and extension, not file name alone ;)
@nakiya good point - I thought i saw "filename without extension" in the question :P
5

Why not let the UriBuilder do the parsing for you?

var url = new UriBuilder("http://x.com/xyz/imgname.img_type_extension?somefield=somevalue"); string filename = Path.GetFileName(url.Path); 

1 Comment

Or perhaps better yet, why not just let Uri do the parsing? My guess is newing up a simple, immutable Uri type would be more performant, but maybe not...?
3

How about

var fNameWithQuery = (imageurl.Split('/'))[(imageurl.Split('/').Length) - 1]; //get first string from array created by splitting substring on occurence of '?' var fNameAndExt = fNameWithQuery.Split('?')[0]; 

Comments

1

Perhaps this?

 string imgUrl = @"C:\blah.jpg"; //Loaded from DB System.IO.FileInfo f = new System.IO.FileInfo(imgUrl); string fileName = f.Name.Split('.')[0]; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.