[英]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.我正在尝试使用我的 ASP.NET web 页面后面的 C# 代码检查服务器上是否存在文件。 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;
}
the file path should be physical not virtual.文件路径应该是物理的而不是虚拟的。 Use
利用
if (File.Exists(Server.MapPath(wordDocName)))
File.Exists()
and probably everything else you want to do with the file will need a real Path. File.Exists()
并且可能您想要对文件执行的所有其他操作都需要一个真实的路径。
Your wordDocName
is a relative URL.您的
wordDocName
是相对的 URL。
Simply use只需使用
string fileName = Server.MapPath(wordDocName);
Use利用
Server.MapPath("~/specifications/" + Convert.ToInt32(ViewState["projectSelected"]) + ".doc")
to get the fully-qualified path.获得完全合格的路径。 That should do the trick for ya.
那应该对你有用。
You need to use Server.MapPath
eg您需要使用
Server.MapPath
例如
wordDocName = Server.MapPath("~/specifications/" + Convert.ToInt32(ViewState["projectSelected"]) + ".doc");
ViewState["wordDocName"] = wordDocName;
if (File.Exists(wordDocName))
{
btnDownloadWordDoc.Visible = true;
}
else
{
btnDownloadWordDoc.Visible = false;
}
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.
我在自己的应用程序中有这种情况,如果我将真实路径放入文件,File.Exists() 返回 true。 But if I use Server.MapPath but the folder is in fact a junction to the folder, it seems to fail.
但是如果我使用 Server.MapPath 但文件夹实际上是文件夹的连接点,它似乎失败了。 Anyone experienced the same behaviour?
有人经历过同样的行为吗?
You have to convert the path to a physical path with Server.MapPath(relativePath)您必须使用 Server.MapPath(relativePath) 将路径转换为物理路径
if (File.Exists(filePath))
wordDocName = "~/specifications/" + ViewState["projectSelected"] + ".doc";
btnDownloadWordDoc.Visible = File.Exists(Server.MapPath(wordDocName));
The character " ~
" is a special char in ASP.NET to get virtual path specifications and simply means " root directory of the application ".字符“
~
”是 ASP.NET 中的一个特殊字符,用于获取虚拟路径规范,简单地表示“应用程序的根目录”。 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. .NET BCL 不理解它,如
File
API 并且必须首先映射到具有Server.MapPath()
的物理路径,如其他所述。
string docname="traintatkalantnoy.txt";
string a = (Server.MapPath(docname)); if (File.Exists(a))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.