Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a file exists on the server

Tags:

c#

file

asp.net

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;
}
like image 300
GreeneScreen Avatar asked Jun 01 '11 16:06

GreeneScreen


People also ask

How do you check a file exists or not?

The exists() function is a part of the File class in Java. This function determines whether the is a file or directory denoted by the abstract filename exists or not. The function returns true if the abstract file path exists or else returns false.

How do you check if a file exists in a server in Python?

Here are a few options: test -e to see if any file exists (directory or regular file), test -f to see if it exists and is a regular file, or test -d to see if it exists and is a directory. This seems to break for paths including $HOME/test or ~/test .

How do you check if a file exists or not in Javascript?

Description. The exists() method of the File object returns a boolean value based on the existence of the file in which it was invoked. If the file exists, the method returns true. It returns false if the file does not exist.

How do I check if a file exists in XML?

This is a way to see if any XML-files exists in that folder, yes. To check for specific files use File. Exists(path) , which will return a boolean indicating wheter the file at path exists. Noe that this answer returns false if the user does not have permission to read the file.


2 Answers

the file path should be physical not virtual. Use

if (File.Exists(Server.MapPath(wordDocName)))
like image 63
amit_g Avatar answered Oct 05 '22 23:10

amit_g


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);
like image 29
Henk Holterman Avatar answered Oct 06 '22 01:10

Henk Holterman