0

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.

5
  • What do you mean by not working? Are you getting an error? Are you not finding the file? Commented May 29, 2013 at 4:50
  • it returns always false Commented May 29, 2013 at 4:51
  • can you show the folder structure of your web application ? Commented May 29, 2013 at 4:53
  • Document/somename/xx.png Commented May 29, 2013 at 4:58
  • For map path to work correctly, you should start your path with ~ Commented May 29, 2013 at 5:02

3 Answers 3

4

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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))
{

}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.