priya77
priya77

Reputation: 175

System.IO.File.Exists() returns false

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.

Upvotes: 1

Views: 6367

Answers (2)

Sune Trudslev
Sune Trudslev

Reputation: 974

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.

Upvotes: 2

lahsrah
lahsrah

Reputation: 9173

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. 
}

Upvotes: 2

Related Questions