我是c#的新手,我正在尝试找到一个可以包含字符串的文件夹,例如:
名称:92011
因此,该文件夹可以是:
- 杰森·莫霍亚 92011
- 92011
- 92011_newOne
等等...
我正在用这段代码做这件事并且工作正常:
string ped = datagridview1.SelectedCells[0].Value.ToString();
string path = @"C:";
DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(path);
FileSystemInfo[] filesAndDirs = hdDirectoryInWhichToSearch.GetFileSystemInfos("*" + ped + "*");
string fullName = "";
foreach (FileSystemInfo foundFile in filesAndDirs)
{
fullName = foundFile.FullName + @"";
Process.Start(fullName);
}
问题是,如果 FileSystemInfo 找到一个文件夹,它会打开它,但如果找不到它,它什么也不做,我希望它说,例如,一条带有"该文件夹不存在"的消息。
如何检查是否在此数据库中找不到文件夹?
由于filesAndDirs
是一个数组,因此可以使用其Length
属性来确定它是否为空。
foreach (FileSystemInfo foundFile in filesAndDirs)
{
fullName = foundFile.FullName + @"";
Process.Start(fullName);
}
if (filesAndDirs.Length == 0)
{
// Nothing was found
}
您可以使用System.Linq
:
bool foundAny = filesAndDirs.Any();
foreach (FileSystemInfo foundFile in filesAndDirs)
{
fullName = foundFile.FullName + @"";
Process.Start(fullName);
}