我的要求是我有一个主文件夹,下面有一组子文件夹。这些子文件夹应具有"FileServer.config"文件。我需要验证这一点,如果文件丢失,请发出一条消息。
主文件夹--> 包含子文件夹 1、子文件夹 02、子文件夹 03。
因此,当用户单击例如SubFolder01时,我想验证该文件是否存在于该文件夹中
目前在代码中,我一次对所有文件夹进行代码扫描,输出基于第一个文件夹
string path =@ "D:TESTPROJRepo";
DirectoryInfo directory = new DirectoryInfo(path);
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach(DirectoryInfo folder in subDirectories)
{
string subpath = Path.Combine( @ "D:TESTPROJRepo", folder.Name);
string[] filePaths = Directory.GetFiles(subpath, "fileserver.config");
if(filePaths.Any())
Console.WriteLine(subpath);
}
这将起作用:
string path = @"D:TESTPROJRepo";
DirectoryInfo directory = new DirectoryInfo(path);
foreach (DirectoryInfo folder in directory.GetDirectories())
{
var files = folder.GetFiles("fileserver.config");
if (files.Length > 0)
Console.WriteLine(folder.Name);
}
你说用户点击了一个子目录(元素(,所以我假设你得到了一个具体的文件夹路径。要验证特定文件夹中是否存在某个文件,请尝试
public bool FileExistsInFolder(string folderPath, string filename)
{
return Directory.Exists(folderPath)
&& Directory.GetFiles(folderPath, fileName).Any();
}