I'm being completely confused here folks,
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 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.
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.
What's going on here?
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.
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 returns false if you do not have permission to access the folder or file referenced. It may be that you can see the file in the immediates window as an administrator, but when running in a different context you do not have permission.
Well, what is the path of your filename? Remember when you build debug and release you compile to different folders. So if you put the file in the debug folder you won't find it when doing a release build.
Try to write it in this way:
if (!Server.Map(fileName))
I have faced this problem too. The problem is that you are binding the path directly in function file.exist("complete path manually")
. Instead of this you should write server.mappath("yourfolder name where file resides")
and then concatenate this with your image.
Try adding ".ToString()" to the path. For example:
if (!File.Exists(fileName.ToString()))
{
throw new ArgumentException("Provided file name does not exist", "fileName");
}
Or if joining strings, place it in brackets, then ".ToString":
if (!File.Exists((filePath + "SomeRandomName").ToString()))
{
throw new ArgumentException("Provided file name does not exist", "fileName");
}
(from question)
I don't quiet understand why ".ToString()" needs to be placed there, but it seems to help...
Hmm, what sort of things are you doing after this check? Make sure you're cleaning up the file state before dragging your breakpoint again.
I had the same problem and found that changing both Debug and Release configurations from AnyCPU to x64 fixed it.
来源:https://stackoverflow.com/questions/2397552/file-exists-returns-false-but-not-in-debug