safi
safi

Reputation: 3766

How can I get a substring from a file path in C#?

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?

Upvotes: 5

Views: 23055

Answers (4)

coldandtired
coldandtired

Reputation: 1043

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.

Upvotes: 4

Bala R
Bala R

Reputation: 108957

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

Upvotes: 12

Aliostad
Aliostad

Reputation: 81660

System.Io.Path.GetFileName(path);

Upvotes: 2

Sean Carpenter
Sean Carpenter

Reputation: 7721

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.

Upvotes: 7

Related Questions