我只想从目录中选择以 NVH 前缀开头的文件名。它不应该从同一目录中选择以 NVHE 开头的文件名。我该怎么做?
我已经尝试了一些东西。它们如下。它们是
//This will store all file names beginning with NVH prefix and NVHE prefix in array
string[] files11 = Directory.GetFiles(moduleDir, "NVH*.*")
.Select(path => Path.GetFileName(path))
.ToArray();
//This will store all file names beginning with NVHE prefix in array only
string[] files12 = Directory.GetFiles(moduleDir, "NVHE*.*")
.Select(path => Path.GetFileName(path))
.ToArray();
现在我只希望文件名以 NVH 开头,而不是 NVHE。我该怎么做?
Directory.GetFiles
does not support regular expressions :
The search string to match against the names of files in path. This parameter can contain a combination of valid literal path and wildcard (* and ?) characters (see Remarks), but doesn't support regular expressions.
或者您可以使用 Directory.EnumerateFiles :
Directory.EnumerateFiles(moduleDir)
.Select(Path.GetFileName)
.Where(file=>file.StartsWith("NVH") && !file.StartsWith("NVHE"));
如果你想保留文件的完整路径:
Directory.EnumerateFiles(moduleDir)
.Where(path=>
{
var file = Path.GetFileName(path);
return file.StartsWith("NVH") && !file.StartsWith("NVHE")
});
您还可以使用现有代码并以这种方式过滤第一个集合:
var result = files11.Except(files12)
我是一名优秀的程序员,十分优秀!