-2

有一个 exe 文件,它可以在驱动器上的任何位置。如何使用 C# 和 WinForms 扫描并判断它是否存在

我尝试了这段代码,但没有让它正常工作

if (Directory.GetFiles(@"C:\", "MCRInstaller.exe", SearchOption.AllDirectories))
{
    // do something. 
}
4

2 回答 2

2
List<string> files = Directory.EnumerateFiles(startFolder, "*.txt",
                                              SearchOption.AllDirectories).ToList();
于 2013-03-17T04:07:46.307 回答
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
}
于 2013-03-17T04:34:29.063 回答