简体   繁体   English

如何从C#中的文件名中删除目录字符串

[英]How to remove directory string from a file name in c#

This is my code 这是我的代码

string[] games = System.IO.Directory.GetFiles(path, "*.exe");            
listBox1.Items.AddRange(games);

Right now it prints out an entire directory as a string. 现在,它以字符串形式打印出整个目录。 I want to get only the file name, so the last part of the directory. 我只想获取文件名,所以要获取目录的最后一部分。 How would I do this? 我该怎么做?

您应该使用Path.GetFileName方法。

You can make use of the FileInfo Class to get that information: 您可以使用FileInfo类来获取该信息:

string[] games = Directory.GetFiles(path, "*.exe")
                          .Select(x => new FileInfo(x).Name)
                          .ToArray();     

You can get this way 你可以这样

string[] games = System.IO.Directory.GetFiles(path, "*.exe");
foreach (var g in games)
{
   listBox1.Items.Add(Path.GetFileName(g));
}

Just try this 试试这个

file_name = Path.GetFileName (your path);

GetFileName will retrun the file name from the path string GetFileName将从路径字符串重新运行文件名

Use System.IO.Path.GetFileName(...) . 使用System.IO.Path.GetFileName(...) Please read the MSDN documentation also. 请同时阅读MSDN文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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