在C#中,
我想要目录名称列表。类型是列表,我有完整的列表(列表fullPathList)。 fullpathList是这样的..
[0] C:\temp\image\a.jpg;
[1] C:\temp\image\b.bmp;
[2] c:\temp\bin\my.exe;
[3] c:\temp\document\resume.doc;
[4] c:\temp\document\timetable.xlsx;
在这种情况下,我想要它。
List<string> dirs;
[0] iamge
[1] bin
[2] document
我想如果我使用正则表达式可能。但是,我不知道详细的方法。
我该怎么办呢? (不要使用循环语句)
我相信这打印出你想要的......
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Test {
class Program {
static void Main(string[] args) {
var files = new string[] {
@"C:\temp\image\a.jpg",
@"C:\temp\image\b.bmp",
@"c:\temp\bin\my.exe",
@"c:\temp\document\resume.doc",
@"c:\temp\document\timetable.xlsx",
};
var dirNames = files.Select(x => new DirectoryInfo(Path.GetDirectoryName(x)).Name);
Debug.WriteLine($"dirNames={string.Join(",", dirNames)}");
}
}
}
Path.GetDirectoryName()返回完整路径和新的DirectoryInfo()。Name只返回路径最后一部分的名称。
如果要将结果放在列表中,请使用...
var dirNames = files.Select(x => new DirectoryInfo(Path.GetDirectoryName(x)).Name).ToList();
检查此解决方案是否有效。它获取指定驱动器中的所有目录。请浏览参考链接ref link
List<string> dir = new List<string>();
System.IO.DriveInfo di = new System.IO.DriveInfo(@"D:\");
System.IO.DirectoryInfo dirInfo = di.RootDirectory;
System.IO.DirectoryInfo[] dirInfos = dirInfo.GetDirectories("*.*");
foreach (System.IO.DirectoryInfo d in dirInfos)
{
dir.Add(d.Name);
}
对于一个真正的文件系统,DirectoryInfo是要走的路。
如果您没有要查询的真实文件系统,但是有一个类似于路径的字符串列表,您可以使用System.IO.Path - Static methods将它们拆分为:
using System;
using System.Linq;
using System.IO;
public class Program
{
public static void Main()
{
// some strings that are like paths
var dirs = new[]
{
@"C:\temp\image\a.jpg", @"C:\temp\image\b.bmp", @"c:\temp\bin\my.exe",
@"c:\temp\document\resume.doc", @"c:\temp\document\timetable.xlsx"
};
// this will use a static method to extract only the path-part
var fullDirs = dirs.Select(d => Path.GetDirectoryName(d)).ToList();
// this will use the same method but split the result at the default systems
// path-seperator char and use only the last part, only uses distinct values
var lastDirsDistinct = dirs.Select(d => Path.GetDirectoryName(d)
.Split(Path.DirectorySeparatorChar).Last()
).Distinct().ToList();
// joins the list with linebreaks and outputs it
Console.WriteLine(string.Join("\n", fullDirs));
// joins the list with linebreaks and outputs it
Console.WriteLine(string.Join("\n", lastDirsDistinct ));
}
}
输出:
C:\temp\image
C:\temp\image
c:\temp\bin
c:\temp\document
c:\temp\document
image
bin
document