简体   繁体   中英

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

I have the following code:

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

When I check the contents of file it has the directory path and extension. Is there a way I can just get the filename out of that?

You can use theFileInfo class:

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

If you want just the file name - quick and simple - use 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类的静态方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM