您能幫我從字符串中找到文件名嗎?現在我有一串像「C:\ xxxx \ xxxx \ xxxx \ abc.pdf」的內容。但我只想要文件名即。 abc.pdf。它將如何通過使用字符串函數獲得?從字符串獲取文件名
3
A
回答
11
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和酒吧不存在。
0
使用方法System.IO.Path,特別是 Path.GetFileName。
4
從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'
0
System.IO.Path.GetFilename(yourFilename) 將返回文件的名稱。
2
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
等
看一看all the members of FileInfo你可能會發現你的需求
相關問題
- 1. C#字符串操作。獲取文件名子字符串
- 2. 從字符串值文件夾中獲取字符串數組?
- 3. 從C#中的URI字符串獲取文件名#
- 4. shell腳本從字符串獲取文件名
- 5. 從JavaScript中的字符串路徑獲取文件名?
- 6. 如何從字符串獲取域名
- 7. 從sql字符串獲取表名
- 8. 獲取名稱(字符串)
- 9. 從字符串獲取子字符串__
- 10. 從EditText獲取文本字符串?
- 11. 從字符串獲取上下文(Android)
- 12. 從文本字符串獲取屬性
- 13. Eclipse插件:從字符串獲取IFile
- 14. 從字符串獲取LCID
- 15. 從字符串獲取DateTime
- 16. 從字符串獲取URL
- 17. 從EditText獲取字符串
- 18. 從spinner獲取字符串
- 19. 從字符串獲取NSDate
- 20. PHP從字符串獲取
- 21. 從字符串獲取keyCode?
- 22. 從CodeBehind獲取字符串
- 23. 從字符串獲取JSONObject
- 24. 從Json獲取字符串
- 25. 從UILabel獲取字符串
- 26. 從字符串獲取值?
- 27. 從字符串中讀取字符或從字符串中獲取字符
- 28. 從文件名中刪除字符串
- 29. 從c#中的字符串中提取列表中的文件名字符串#
- 30. 從字符串獲取特定字符
@Dilse Naaz一些有趣的事情:我不明白你的評論,我害怕。我顯示的代碼處理字符串。 – 2010-04-30 06:37:16