问题
i'm trying to see if the picture exists but this says that isnt there, and the path is correct! The path is correct, and it has a picture, but this allways go to "else".
string path = @"c:\folder\pic.jpg";
if (File.Exists(path))
{
//Do something here
}
else
{
}
回答1:
It may be a permissions issue. From the documentation:
If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path.
Of course, this means you're more likely to see this issue when you're running a web app (which typically runs under reduced permissions) than a client app.
Additionally, as noted in deerchao's comment, File.Exists only returns true if the path given is to a file, not a directory. Again, from the documentation:
If path describes a directory, this method returns false.
回答2:
You are trying to see if a folder exists using File.Exists. This is not correct - it will fail for directories.
Use Directory.Exists for finding if a directory exists.
string path = @"c:\folder";
if (Directory.Exists(path))
{
//Do something here
}
else
{
}
An additional complication is that the account your application is running under needs to have the permissions to read the path - if it doesn't have the permissions, this will still fail even if the path exists.
回答3:
I assume you are trying to check whether any file exists within the specified directory? In that case, you may use:
string path = @"c:\folder";
if (Directory.Exists(path) &&
Directory.GetFiles(path).Any())
{
//Do something here
}
else
{
}
In .NET 4 and later, you may optimize the second check by replacing the GetFiles call with EnumerateFiles.
来源:https://stackoverflow.com/questions/10676391/file-exists-wrong