[英]How do I retrieve all filenames in a directory?
How do I retrieve all filenames matching a pattern in a directory? 如何检索与目录中的模式匹配的所有文件名? I tried this but it returns the full path instead of the filename.
我试过这个,但它返回完整路径而不是文件名。
Directory.GetFiles (path, "*.txt")
Do I have to manually crop the directory path off of the result? 我是否必须手动裁剪结果的目录路径? It's easy but maybe there is an even simpler solution :)
它很简单,但也许有一个更简单的解决方案:)
foreach (string s in Directory.GetFiles(path, "*.txt").Select(Path.GetFileName))
Console.WriteLine(s);
Assuming you're using C#, the DirectoryInfo class will be of more use to you: 假设您正在使用C#,DirectoryInfo类将对您更有用:
DirectoryInfo directory = new DirectoryInfo(path);
FileInfo[] files = directory.GetFiles("*.txt");
The FileInfo class contains a property Name
which returns the name without the path. FileInfo类包含一个属性
Name
,它返回不带路径的名称。
See the DirectoryInfo documentation and the FileInfo documentation for more information. 有关详细信息,请参阅DirectoryInfo文档和FileInfo文档 。
Do you want to recurse through subdirectories? 你想通过子目录进行递归吗? Use
Directory.EnumerateFiles
: 使用
Directory.EnumerateFiles
:
var fileNames = Directory.EnumerateFiles(@"\", "*.*", SearchOption.AllDirectories);
Use Path.GetFileName with your code: 将Path.GetFileName与您的代码一起使用:
foreach(var file in Directory.GetFiles(path, "*.txt"))
{
Console.WriteLine(Path.GetFileName(file));
}
Another solution: 另一种方案:
DirectoryInfo dir = new DirectoryInfo(path);
var files = dir.GetFiles("*.txt");
foreach(var file in files)
{
Console.WriteLine(file.Name);
}
var filenames = Directory.GetFiles(@"C:\\Images", "*.jpg").
Select(filename => Path.GetFileNameWithoutExtension(filename)).
ToArray();
Try this if it is what you want 如果它是你想要的,试试这个
You can use the following code to obtain the filenames: 您可以使用以下代码获取文件名:
DirectoryInfo info = new DirectoryInfo("C:\Test");
FileInfo[] files = info.GetFiles("*.txt");
foreach(FileInfo file in files)
{
string fileName = file.Name;
}
Try this 试试这个
IEnumerable<string> fileNames =
Directory.GetFiles(@"\\srvktfs1\Metin Atalay\", "*.dll")
.Select(Path.GetFileNameWithoutExtension);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.