簡體   English   中英

從字符串中獲取文件名

[英]Getting File name from the String

你能幫我從字符串中找到文件名嗎? 現在我有一串內容,如“C:\\xxxx\\xxxx\\xxxx\\abc.pdf”。 但我只想要文件名,即。 abc.pdf。 使用字符串函數將如何獲得?

使用Path.GetFileName

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

請注意,這假定名稱的最后一部分是文件 - 它不檢查。 所以如果你給它“C:\\Windows\\System32”,它會聲明一個 System32 的文件名,即使那實際上是一個目錄。 (但是, File.Exists "C:\\Windows\\System32\\" 將返回一個空字符串。)如果有幫助,您可以使用File.Exists來檢查文件是否存在並且是文件而不是目錄

此方法也不檢查目錄層次結構中的所有其他元素是否存在 - 因此您可以傳入“C:\\foo\\bar\\baz.txt”,即使 foo 和 bar 不存在,它也會返回 baz.txt存在。

使用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'

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 的所有成員,您可能會發現一些有趣的內容滿足您的需求

使用System.IO.Path的方法,尤其是Path.GetFileName

System.IO.Path.GetFilename(yourFilename) 將返回文件的名稱。

你可以使用:

System.IO.Path.GetFileNameWithoutExtension("C:\xxxx\xxxx\xxxx\abc.pdf")

你會回來abc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM