Reputation: 653
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
Reputation: 31270
the file path should be physical not virtual. Use
if (File.Exists(Server.MapPath(wordDocName)))
Upvotes: 49
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
Reputation: 1
string docname="traintatkalantnoy.txt";
string a = (Server.MapPath(docname));
if (File.Exists(a))
Upvotes: -3
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
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
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
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
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