Store the name but not the path of all folders in a specified folder to a list?

So I have a folder in the same directory as my .exe console application. I want to make a list of all the folders inside of that folder (it's called ClientFiles ) but I don't want the full paths. So if I have a hierarchy like this:

ClientFiles

--- Folder1

--- Folder2

--- Folder3

I should end up with a list containing the strings: "Folder1", "Folder2", "Folder3".

This is what I have right now:

List<string> clientNumbers = Directory
  .GetDirectories(AppDomain.CurrentDomain.BaseDirectory + "ClientFiles")
  .ToList<string>();

but the list it's returning contains the full path for each element. Any quick way to resolve this? I guess I could foreach through and remove the preceding path text but that seems so extra.


There are a few ways that you can accomplish this.

The first is simply removing the component you already know:

string directory = AppDomain.CurrentDomain.BaseDirectory + "ClientFiles";
List<string> clientNumbers = Directory
  .GetDirectories(directory)
  .Select(x => x.Substring(AppDomain.CurrentDomain.BaseDirectory.Length - 1)
  .ToList();

Assuming you only want the file's name (or folder's name if it's a folder object), you can use the Path class

List<string> clientNumbers = Directory
  .GetDirectories(directory)
  .Select(x => Path.GetFileName(x))
  .ToList();

有了一点LINQ:

List<string> clientNumbers = System.IO.Directory.GetDirectories(AppDomain.CurrentDomain.BaseDirectory + "ClientFiles")
.Select(x => x.Replace(AppDomain.CurrentDomain.BaseDirectory + "ClientFiles", "")).ToList();

您可以在.Select(x=>x.Split('').LastOrDefault())添加.Select(x=>x.Split('').LastOrDefault()) ,例如:

List<string> clientNumbers = Directory.GetDirectories(AppDomain.CurrentDomain.BaseDirectory + "ClientFiles").ToList<string>()
   .Select(x=>x.Split('').LastOrDefault());
链接地址: http://www.djcxy.com/p/36092.html

上一篇: 访问远程服务器上的文件

下一篇: 将名称而不是指定文件夹中所有文件夹的路径存储到列表中?