Getting file name from string

Could you help me find the file name from the string. Now I have one line of content, such as "C: \ xxxx \ xxxx \ xxxx \ abc.pdf". But I want only the ie file name. abc.pdf. How does this come about with string functions?

+3
source share
5 answers

Use Path.GetFileName:

string full = @"C:\xxxx\xxxx\xxxx\abc.pdf";
string file = Path.GetFileName(full);
Console.WriteLine(file); // abc.pdf

, , - - . , "C:\Windows\System32", System32, . ( "C:\Windows\System32 \" .) File.Exists, , , , .

, "C:\foo\bar\baz.txt", baz.txt, foo bar .

+11

Path.GetFileName()

() MSDN-:

string fileName = @"C:\xxxx\xxxx\xxxx\abc.pdf";
string path = @"C:\xxxx\xxxx\xxxx\";
string path2 = @"C:\xxxx\xxxx\xxxx";

string result;

result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    fileName, result);

result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    path, result);

result = Path.GetFileName(path2);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    path2, result);

, :

GetFileName('C:\xxxx\xxxx\xxxx\abc.pdf') returns 'abc.pdf'
GetFileName('C:\xxxx\xxxx\xxxx\') returns ''
GetFileName('C:\xxxx\xxxx\xxxx') returns 'xxxx'
+4

Sytem.IO.FileInfo :

FileInfo fi = new FileInfo("C:\xxxx\xxxx\xxxx\abc.pdf");
string name = fi.Name; // it gives you abc.pdf

:
? fi.Exists
? . fi.Extension
? . fi.Directory
.

FileInfo, -

+2

System.IO.Path.GetFilename(yourFilename) .

0

Source: https://habr.com/ru/post/1743455/


All Articles