GreeneScreen
GreeneScreen

Reputation: 653

Check if a file exists on the server

I am trying to check if a file is on the server with the C# code behind of my ASP.NET web page. I know the file does exist as I put it on the server in a piece of code before hand. Can anyone see why it is not finding the file. This is the code:

wordDocName = "~/specifications/" + Convert.ToInt32(ViewState["projectSelected"]) + ".doc";
ViewState["wordDocName"] = wordDocName;
if (File.Exists(wordDocName))
{
    btnDownloadWordDoc.Visible = true;
}
else
{
    btnDownloadWordDoc.Visible = false;
}

Upvotes: 16

Views: 52852

Answers (8)

amit_g
amit_g

Reputation: 31270

the file path should be physical not virtual. Use

if (File.Exists(Server.MapPath(wordDocName)))

Upvotes: 49

Cristian Cotovan
Cristian Cotovan

Reputation: 1090

this might not work if the directory holding the file is referenced by a junction/symbolic link. I have this case in my own application and if I put the REAL path to the file, File.Exists() returns true. But if I use Server.MapPath but the folder is in fact a junction to the folder, it seems to fail. Anyone experienced the same behaviour?

Upvotes: 1

karthikeyan r
karthikeyan r

Reputation: 1

string docname="traintatkalantnoy.txt";

string a = (Server.MapPath(docname)); if (File.Exists(a))

Upvotes: -3

slfan
slfan

Reputation: 9139

You have to convert the path to a physical path with Server.MapPath(relativePath)

if (File.Exists(filePath))

wordDocName = "~/specifications/" + ViewState["projectSelected"] + ".doc";        
btnDownloadWordDoc.Visible = File.Exists(Server.MapPath(wordDocName));

Upvotes: 0

codymanix
codymanix

Reputation: 29540

The character "~" is a special char in ASP.NET to get virtual path specifications and simply means "root directory of the application". Is is not understood by the .NET BCL like the File API and must be mapped first into a physical path with Server.MapPath() as others stated.

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273854

File.Exists() and probably everything else you want to do with the file will need a real Path.

Your wordDocName is a relative URL.

Simply use

string fileName = Server.MapPath(wordDocName);

Upvotes: 2

Binary Worrier
Binary Worrier

Reputation: 51739

You need to use Server.MapPath e.g.

    wordDocName = Server.MapPath("~/specifications/" + Convert.ToInt32(ViewState["projectSelected"]) + ".doc");
    ViewState["wordDocName"] = wordDocName;
    if (File.Exists(wordDocName))
    {
        btnDownloadWordDoc.Visible = true;
    }
    else
    {
        btnDownloadWordDoc.Visible = false;
    }

Upvotes: 1

Keith
Keith

Reputation: 5391

Use

Server.MapPath("~/specifications/" + Convert.ToInt32(ViewState["projectSelected"]) + ".doc")

to get the fully-qualified path. That should do the trick for ya.

Upvotes: 1

Related Questions