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开发者_StackOverflow社区 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:
DirectoryInfo directory = new DirectoryInfo(path);
FileInfo[] files = directory.GetFiles("*.txt");
The FileInfo class contains a property Name which returns the name without the path.
See the DirectoryInfo documentation and the FileInfo documentation for more information.
Do you want to recurse through subdirectories?  Use Directory.EnumerateFiles:
var fileNames = Directory.EnumerateFiles(@"\", "*.*", SearchOption.AllDirectories);
Use Path.GetFileName with your code:
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);
}
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;
    }
var filenames = Directory.GetFiles(@"C:\\Images", "*.jpg").
                Select(filename => Path.GetFileNameWithoutExtension(filename)).
                ToArray();
Try this if it is what you want
Try this
IEnumerable<string> fileNames =
                Directory.GetFiles(@"\\srvktfs1\Metin Atalay\", "*.dll")
                    .Select(Path.GetFileNameWithoutExtension);
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论