C# File.Exists returns false,文件确实存在

C# File.Exists returns false, file does exist

使用 VS 15,C# 和 .Net 4.5.2
计算机在 AD 网络上,广告名称为 "AD"。
AD 普通用户权限、AD 管理员权限和本地管理员权限会出现此问题。不管程序获得什么权限,都会出现同样的问题。

我们的测试文件是“C:/windows/system32/conhost.exe”.
上面的文件存在,它非常存在。我可以用资源管理器看到它。

这是资源管理器中的文件:

这是文件属性:

你可以看到它在那里,对吧?
以下 cmd 命令检查文件是否存在:

IF EXIST "C:\windows\system32\conhost.exe" (echo does exist) ELSE (echo doesnt exist)

它returns“确实存在”如许。

以下 C# 代码检查文件是否存在:

FileInfo file = new FileInfo("C:/windows/system32/conhost.exe");
MessageBox.Show(file.Exists + "");

这个returns“”。

此代码也returns "False":

MessageBox.Show(File.Exists("C:/windows/system32/conhost.exe") + "");

这段代码也没有找到:

foreach (string file in Directory.GetFiles("C:/windows/system32/"))
{
    //conhost is NEVER mentioned, like it doesn't exist
}

这段代码也没有找到:

foreach (string file in Directory.EnumerateFiles("C:/windows/system32/"))
{
    //conhost is NEVER mentioned, like it doesn't exist
}

错,错,错:

MessageBox.Show(File.Exists("C:/windows/system32/conhost.exe") + "");
MessageBox.Show(File.Exists("C:\windows\system32\conhost.exe") + "");
MessageBox.Show(File.Exists(@"C:\windows\system32\conhost.exe") + "");

我做错了什么?
额外注意:我将 conhost 复制到 C:\conhost.exe,我的程序可以毫无问题地找到它。我的程序还在 system32 中找到其他文件,只是没有找到 conhost 和其他一些文件。比如找到system32的"connect.dll",所以不是目录的读权限
更多额外说明:conhost.exe 和 connect.dll 具有相同的安全属性(文件属性中的安全选项卡)。

System.IO.File.Exists(path) 的 MSDN 文档中,它指出:

If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path.

因此,我们可以安全地假设您的应用程序没有对该特定文件的读取权限。检查安全设置并授予读取权限(如果尚未这样做)。

构建您的应用程序(在发布模式下)并运行作为管理员。

如果您使用的是 x64 系统,您将在 c:\Windows\System32 目录中为 x86 和 x64 应用程序提供不同的内容。请确保您使用的是相同的架构 运行 批处理文件和您的 C# 应用程序。

这是 64 位操作系统出现的问题...这里有一个解决方法,

转到项目的属性 > 单击构建选项卡 > 取消选中首选 32 位

之后,它应该可以在 64 位 os 上正常工作。

在大多数情况下,这确实提供了预期的结果。

FileInfo f = new FileInfo(@"C:\Program Files\Microsoft Office\root\Office16\MSACCESS.EXE");
if (f.Exists) 
   {
    ... do something; 
   }