Only writing the relative filename from the full file name c#

70 views Asked by At

So I do not know if this is possible, but below I have a file path in a variable path:

string path = @"c:\users\povermyer\documents\visual studio 2013\Projects\DanProject\PNRS
\PNRS.log";

What I want to do is I want to have the console window write just the last part in the path. For example, I would like the output of the console window to be:

The name of this file is PNRS.log

Is there a way to do that simply, or am I going to have to do it a long way by using a directory?

3

There are 3 answers

0
Habib On BEST ANSWER

Use Path.GetFileName method.

var fileName = Path.GetFileName(path);
4
maraaaaaaaa On

or:

string path = 
    @"c:\users\povermyer\documents\visual studio 2013\Projects\DanProject\PNRS\PNRS.log";

string fileName = path.Split('\\').Last();
1
bumble_bee_tuna On

You could use:

string path = 
    @"c:\users\povermyer\documents\visual studio 2013\Projects\DanProject\PNRS\PNRS.log";
var fileName = Path.GetFileName(path);