簡體   English   中英

我怎樣才能從這個 C# 代碼中獲取基本文件名?

[英]How can I just get the base filename from this C# code?

我有以下代碼:

string[] files = Directory.GetFiles(@"C:\Notes", "*.txt", SearchOption.TopDirectoryOnly);
foreach(string file in files)

當我檢查文件的內容時,它具有目錄路徑和擴展名。 有沒有辦法我可以從中獲取文件名?

您可以使用FileInfo類:

FileInfo fi = new FileInfo(file);
string name = fi.Name;

如果你想要文件名 - 快速簡單 - 使用Path

string name = Path.GetFileName(file);

您可以使用以下方法: Path.GetFileName(file)

System.IO.FileInfo f = new System.IO.FileInfo(@"C:\pagefile.sys");  // Sample file.
System.Windows.Forms.MessageBox.Show(f.FullName);  // With extension.
System.Windows.Forms.MessageBox.Show(System.IO.Path.GetFileNameWithoutExtension(f.FullName));  // What you wants.

如果您需要去除擴展名、路徑等,您應該將此字符串填充到FileInfo並使用其屬性或使用Path類的靜態方法。

暫無
暫無

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

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