System.IO.File.Exists() returns false

2019-08-08 09:28发布

问题:

I have a page where I need to display an image which is stored on the server. To find that image, I use the following code:

 if (System.IO.File.Exists(Server.MapPath(filepath)))

When I use this, I get a proper result as the file is present.

But when I give an absolute path like below:

 if (System.IO.File.Exists("http://myserever.address/filepath"))

It returns false.

The file is physically present there, but I don't know why it's not found.

回答1:

The path parameter for the System.IO.File.Exists is the path to an actual file in the file system.

The call to Server.MapPath() changes the URI into an actual file path.

So it is working as intended.



回答2:

You can't use HTTP paths in File.Exists. It supports network shares and local file systems. If you want to do this in a web application on the server side. First use Server.MapPath() first to find the physical location and then use File.Exists.

Read about Server.MapPath here: http://msdn.microsoft.com/en-us/library/ms524632%28v=vs.90%29.aspx

Eg.

string filePath = ResolveUrl("~/filepath/something.jpg");

if (File.Exists(Server.MapPath(filePath)))
{
     //Do something. 
}