如何在C#中获取目录中的文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/862416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:39:43  来源:igfitidea点击:

How to get the name of File in a directory in C#

c#

提问by SyncMaster

Directory.GetFiles(targetDirectory);

Using the above code we get the names(i.e full path)of all the files in the directory. but i need to get only the name of the file and not the path. So how can I get the name of the files alone excluding the path? Or do I need to do the string operations in removing the unwanted part?

使用上面的代码我们得到目录中所有文件的名称(即完整路径)。但我只需要获取文件名而不是路径。那么如何单独获取文件的名称,不包括路径?或者我是否需要执行字符串操作来删除不需要的部分?

EDIT:

编辑:

TreeNode mNode = new TreeNode(ofd.FileName, 2, 2);

Here ofdis a OpenFileDialogand ofd.FileNameis giving the the filename along with it's Path but I need the file name alone.

ofd是一个OpenFileDialogofd.FileName给出了文件名及其路径,但我只需要文件名。

采纳答案by ChrisF

You could use:

你可以使用:

Path.GetFileName(fullPath);

or in your example:

或在您的示例中:

TreeNode mNode = new TreeNode(Path.GetFileName(ofd.FileName), 2, 2);

回答by SO User

Use DirectoryInfo and FileInfo if you want to get only the filenames without doing any manual string editing.

如果您只想获取文件名而不进行任何手动字符串编辑,请使用 DirectoryInfo 和 FileInfo。

DirectoryInfo dir = new DirectoryInfo(dirPath);
foreach (FileInfo file in dir.GetFiles())
    Console.WriteLine(file.Name);

回答by Anton

Use:

用:

 foreach(FileInfo fi in files)
 {
     Response.Write("fi.Name");       
 }