[英]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. 所以我在.exe控制台应用程序所在的目录中有一个文件夹。 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. 我想列出该文件夹内的所有文件夹(它叫做ClientFiles
),但我不想要完整的路径。 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". 我应该得到一个包含字符串的列表:“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. 我想我可以通过并删除前面的路径文本,但这似乎是额外的。
With a bit of LINQ: 有点LINQ:
List<string> clientNumbers = System.IO.Directory.GetDirectories(AppDomain.CurrentDomain.BaseDirectory + "ClientFiles\\")
.Select(x => x.Replace(AppDomain.CurrentDomain.BaseDirectory + "ClientFiles\\", "")).ToList();
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 假设您只想要文件的名称(或文件夹的名称,如果它是文件夹对象),您可以使用Path
类
List<string> clientNumbers = Directory
.GetDirectories(directory)
.Select(x => Path.GetFileName(x))
.ToList();
You can add .Select(x=>x.Split('\\').LastOrDefault())
at the end such as: 您可以在.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());
Use a LINQ lambda expression: 使用LINQ lambda表达式:
List<string> clientNumbers = Directory.GetDirectories(
AppDomain.CurrentDomain.BaseDirectory + "ClientFiles\\")
.ToList<string>().Select(s=>s.Split("\\").Last());
LastOrDefault will return same, as string is nullable LastOrDefault将返回相同的值,因为字符串可以为空
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.