File.Exists()返回false,但不是在调试 [英] File.Exists() returns false, but not in debug

查看:309
本文介绍了File.Exists()返回false,但不是在调试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是完全糊涂了这里的乡亲,

I'm being completely confused here folks,

我的code抛出一个异常,因为File.Exists()返回false

My code throws an exception because File.Exists() returns false

public override sealed TCargo ReadFile(string fileName)
{
    if (!File.Exists(fileName))
    {
        throw new ArgumentException("Provided file name does not exist", "fileName");
    }

Visual Studio中休息的throw语句,我立即检查立即窗口 File.Exists(文件名)的价值。它返回。当我拖了断点恢复到if语句,然后再执行它,它再次抛出。

Visual studio breaks at the throw statement, and I immediately check the value of File.Exists(fileName) in the immediate window. It returns true. When I drag the breakpoint back up to the if statement and execute it again, it throws again.

文件名是一个绝对路径的文件。我没有创建该文件,也没有写它(它的存在一直)。如果我粘贴路径到记事本中打开的对话​​框,它会读取该文件没有问题。

fileName is an absolute path to a file. I'm not creating the file, nor writing to it (it's there all along). If I paste the path into the open dialog in Notepad, it reads the file without problems.

在code正在执行一个后台工作。这是唯一的复杂因素,我能想到的。我肯定的文件尚未已经打开,无论是在工作线程或其他地方。

The code is executing in a background worker. It's the only complicating factor I can think of. I am positive the file has not been opened already, either in the worker thread or elsewhere.

这是怎么回事吗?

推荐答案

我不知道发生了什么事情,但你为什么需要File.Exists测试呢?什么你真正感兴趣的是,我可以的阅读本文件的?大量的比未找到文件以外的其他事情都可能出错。

I don't know what's going on, but why do you need the File.Exists test at all? What you're really interested in is, "Can I read this file?" Plenty of other things other than File Not Found can go wrong.

更何况,做一个File.Exists测试是一种竞争状态,因为该文件可能会消失,你已经做了测试之后,但在打开文件之前。只要打开该文件,这是你可以做,以确定是否可以读取文件的最好的测试。

Not to mention, doing a File.Exists test is a race condition because the file could go away after you've done the test, but before you open the file. Just open the file, that's the best test you can do to determine whether you can read the file.

这篇关于File.Exists()返回false,但不是在调试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆