简体   繁体   中英

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:

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

Use System.IO.Path.GetFileName(...) . Please read the MSDN documentation also.

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