File.Exists("")和FileInfo之间存在什么区别

Bar*_*try 12 .net c# virtualization

我在\ ProgramFiles(x86)\ MyAppFolder中有一个*.exe文件.

在x86应用程序中,我检查文件是否存在(64位系统).简单:

bool fileExists = File.Exists(@"\ProgramFiles(x86)\MyAppFolder\Manager.exe");
Run Code Online (Sandbox Code Playgroud)

结果是:"fileExists == false"(文件确实存在).据我所知,这是虚拟化.这里描述的问题很好.但下一个代码:

bool fileExists = new FileInfo("\\Path").Exists;
Run Code Online (Sandbox Code Playgroud)

"fileExists == true"

为什么在第一和第二种情况下结果不同?

var controller = new ServiceController(Product.ServiceName);
_manager.Enabled = controller.Status == ServiceControllerStatus.Running;

var info = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);

var s = File.Exists(@"D:\TFS\GL_SOURCES\Teklynx_LPM\Dev\Server\Debug\Manager.exe");

string pathToManager = string.Empty;

if (info.Parent != null)
{
    var pathToModule = info.Parent.FullName;
    pathToManager = Path.Combine(pathToModule,"Manager.exe").Replace(" ",string.Empty);
}
Run Code Online (Sandbox Code Playgroud)

//效果很好

var fileInfo = new FileInfo(pathToManager);
var managerSeparator = new ToolStripSeparator()
{
    Visible = _manager.Visible = fileInfo.Exists // true
};
Run Code Online (Sandbox Code Playgroud)

//不起作用

var managerSeparator = new ToolStripSeparator()
{
    Visible = _manager.Visible = File.Exists(pathToManager ) // false
};
Run Code Online (Sandbox Code Playgroud)

谢谢!

Dav*_*ret 23

这是唯一的区别,它更多地与以下性质有关FileInfo:

FileInfo fileInfo = new FileInfo("myFile.txt"); // non-existent file
Console.WriteLine(fileInfo.Exists);             // false
File.Create("myFile.txt");
Console.WriteLine(File.Exists("myFile.txt"));   // true
Console.WriteLine(fileInfo.Exists);             // false
Run Code Online (Sandbox Code Playgroud)

因此,您可以fileInfo.Exists在第一次使用时看到缓存的值.

除此之外,他们在幕后做同样的事情.

  • 这实际上是行为的关键差异!从表面上看,我很确定大多数人会根据文件的当前状态而不是文件的某些缓存状态来预期失败或成功. (5认同)
  • `fileInfo.Refresh()`将清除其缓存. (4认同)

Han*_*ant 15

没有区别,这些方法在.NET Framework中使用完全相同的内部帮助器方法.使用反编译器或Reference Source源代码可以看到的东西,辅助方法名称是File.FillAttributeInfo().

在.NET Framework中具有这样的重复是非常不寻常的,并不是一个很好的事情,有多种方法来完成同样的事情.然而,File类是特殊的,它是在.NET 1.0发布之前进行的可用性研究之后添加的.测试对象只需要使用基本的BCL类,如FileStream和FileInfo,否则只有MSDN文档可用.测试结果不是很好,File类被添加以帮助程序员陷入成功的陷阱,编写非常基本的文件操作代码.像File.Exists()和File.ReadAllLines().

因此它与类没有任何关系,你只是错误地使用它们.就像没有实际使用相同的路径.在正斜杠上很容易,在Windows中发生向后斜线的映射,并且在其他代码中不一致地实现.使用//肯定不会做你希望它做的事情.