File.Exists () returns false, but not in debugging

People here completely confuse me,

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 down into a throw statement, and I immediately check the value of File.Exists(fileName) in the immediate window. It returns true . When I drag the breakpoint into the if statement and execute it again, it throws again.

fileName is the absolute path to the file. I do not create a file or write to it (it is there all the time). If I paste the path into an open dialog in Notepad, it will read the file without any problems.

The code runs in the background worker. This is the only difficult factor that I can think of. I am sure that the file was no longer open, either in the workflow or elsewhere.

What's going on here?

+4
source share
7 answers

I do not know what is happening, but why do we need the File.Exists test? What you are really interested in is: "Can I read this file?" Many other things besides File Not Found can go wrong.

Not to mention that running the File.Exists test is a race condition, because the file may disappear after you run the test, but before you open the file. Just open the file, which is the best test you can do to determine if you can read the file.

+12
source

File.Exists returns false if you do not have permission to access the specified folder or file. Perhaps you can see the file in the immediate window as an administrator, but when working in a different context, you do not have permission.

+6
source

Well, what is the path of your file name? Remember when you create a debug version and send it to different folders. Therefore, if you put the file in the debug folder, you will not find it when creating the assembly.

+1
source

I also ran into this problem. The problem is that you bind the path directly in the file.exist("complete path manually") function. Instead, you should write server.mappath("yourfolder name where file resides") and then connect this to your image.

+1
source

Try adding ".ToString ()" to the path. For instance:

 if (!File.Exists(fileName.ToString())) { throw new ArgumentException("Provided file name does not exist", "fileName"); } 

Or, if you append strings, put them in brackets, then ".ToString":

 if (!File.Exists((filePath + "SomeRandomName").ToString())) { throw new ArgumentException("Provided file name does not exist", "fileName"); } 

(from the question)

I don’t understand why ".ToString ()" needs to be put there, but it seems to help ...

+1
source

Try to write like this:

 if (!Server.Map(fileName)) 
+1
source

Hmm, what are you doing after this check? Before dragging a breakpoint, make sure you clear the state of the file.

0
source

Source: https://habr.com/ru/post/1303405/


All Articles