Milton
Milton

Reputation: 171

Check file exists or not using c#

I stored a file path in database table like this ../Document/5292013/cal.png. Now I want to check whether or not the file exists in the server folder. I am using the below code to check this, but it's not working for me.

 if (File.Exists(Server.MapPath(root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText)))
 {
     proof.HRef = Server.MapPath(root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText);
 }

Now I check using watch File.Exists(Server.MapPath("Document")) //Returns false, but server having the same folder.

Please help me to solve this.

Upvotes: 0

Views: 1703

Answers (3)

Hitesh
Hitesh

Reputation: 1228

First you have to get filepath (filename) from database using select query then use that path with file.exists.

Example:

First get filename or filepath from database then,

if you get only filename then use below code:

if(File.Exits(Server.MapPath("Document/5292013/"+filename)))
{
}

or if you get only filepath then use below code:

if(File.Exits(Server.MapPath("filename")))
{
}

Thanks

Upvotes: 0

Igor
Igor

Reputation: 15893

You need to transform the file name to a virtual form before using MapPath. You must know the specifics of how it needs to be done. For example:

string fileName = root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText;
fileName = fileName.Replace("..", "~");
if (File.Exists(Server.MapPath(fileName))
{
    // you probably do not want MapPath here:
    //proof.HRef = Server.MapPath(root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText);
    proof.HRef = System.Web.VirtualPathUtility.ToAbsolute(fileName);
}

Upvotes: 4

sameh.q
sameh.q

Reputation: 1709

Try to print out Server.MapPath(root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText) it might be pointing a wrong path or something

Any way, checking a file if it exists or not is very trivial:

if(File.Exists(the file path))
{

}

Upvotes: 1

Related Questions