有一个exe文件,它可以在驱动器上的任何位置。如何使用C#和WinForms
扫描并判断它是否存在我尝试了这段代码,但没有让它正常工作
if (Directory.GetFiles(@"C:\", "MCRInstaller.exe", SearchOption.AllDirectories))
{
// do something.
}
答案 0 :(得分:2)
List<string> files = Directory.EnumerateFiles(startFolder, "*.txt",
SearchOption.AllDirectories).ToList();
答案 1 :(得分:1)
您可能还想知道在点击系统文件夹(系统卷信息,RECYCLER,Windows等)时会抛出异常。
考虑一些排除,如下面的lambda:
List<string> matches = new List<string>();
DirectoryInfo C = new DirectoryInfo("C:\\");
var rootFiles = C.GetFiles();
var rootDirs = C.GetDirectories("*", SearchOption.TopDirectoryOnly).Where(dir => !dir.Name.Equals("System Volume Information") && !dir.Name.Equals("RECYCLER") && !dir.Name.Equals("WINDOWS"));
foreach (var rf in rootFiles)
{
if (rf.Name.Equals("MCRInstaller.exe"))
{
matches.Add(rf.FullName);
}
}
foreach (var rdir in rootDirs)
{
try
{
var dirFiles = rdir.GetFiles("*", SearchOption.AllDirectories);
foreach (var aFile in dirFiles)
{
if (aFile.Name.Equals("MCRInstaller.exe"))
{
matches.Add(aFile.FullName);
}
}
}
catch (UnauthorizedAccessException err)
{
using (StreamWriter errLog = File.AppendText("errors.log"))
{
string dt = "[" + DateTime.Now + "]: ";
errLog.Write(dt);
errLog.Write(err.StackTrace);
}
}
}
foreach (string match in matches)
{
//do some stuff with your list of matches
}