可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
Try to write it in this way:
if (!Server.Map(fileName))
回答5:
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.
回答6:
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...
回答7:
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.