开发者

Check if a file exists on the server

开发者 https://www.devze.com 2023-03-10 05:06 出处:网络
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

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开发者_如何学JAVA/" + 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.

Your wordDocName is a relative 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 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;
    }


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?


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.


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


string docname="traintatkalantnoy.txt";

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

0

精彩评论

暂无评论...
验证码 换一张
取 消