繁体   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