5

I have a string path = c:\inetpub\wwwrroot\images\pdf\admission.pdf

I am using this

path = path.LastIndexOf("\\").ToString();
path = path.Substring(path.LastIndexOf("/") + 1);

i want to get:

c:\inetpub\wwwrroot\images\pdf
c:\inetpub\wwwrroot\images\pdf\admission.pdf

now i want to get the admission.pdf from this string path how can i do it?

1
  • 5
    You should still use one of the IO.Path functions. Doing this manually with String.Substring is just asking for trouble. Commented Feb 26, 2011 at 13:54

4 Answers 4

12
string path = "c:\\inetpub\\wwwrroot\\images\\pdf\\admission.pdf";

string folder = path.Substring(0,path.LastIndexOf(("\\")));
                // this should be "c:\inetpub\wwwrroot\images\pdf"

var fileName = path.Substring(path.LastIndexOf(("\\"))+1);
                // this should be admin.pdf
Sign up to request clarification or add additional context in comments.

3 Comments

@safi: No, it didn’t. You should listen to the highest-voted answer.
@Timwi the OP specifically asked for a solution using Substring in one of his comments and that's why I posted by answer with Substring. Maybe he's got a good reason for that. Thanks for the down-vote.
Please stop assuming that everyone who comments negatively also downvoted you.
7

There are a bunch of helper methods on the System.IO.Path class for extracting parts of paths/filenames from strings.

In this case, System.IO.Path.GetFileName will get you what you want.

4 Comments

yes but i want to use substring method, not the file path object :)
Why is that? This method gets you the filename without having to deal with substring and calculating string positions yourself.
because i am further using this string to rename a file, so some time it might be a folder name as well.
@safi: You should use Path.GetFileName regardless. It works with directory names too.
4

Why Substring?

Use

System.Io.Path.GetDirectoryName(full_filepath)

to get the folder name, and

System.Io.Path.GetFileName(full_filepath)

for just the file.

Comments

2
System.Io.Path.GetFileName(path);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.