[英]Check file exists or not using c#
I stored a file path in database table like this ../Document/5292013/cal.png
. 我在
../Document/5292013/cal.png
这样的数据库表中存储了文件路径。 Now I want to check whether or not the file exists in the server folder. 现在,我要检查服务器文件夹中是否存在该文件。 I am using the below code to check this, but it's not working for me.
我正在使用以下代码进行检查,但对我来说不起作用。
if (File.Exists(Server.MapPath(root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText)))
{
proof.HRef = Server.MapPath(root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText);
}
Now I check using watch File.Exists(Server.MapPath("Document")) //Returns false
, but server having the same folder. 现在,我使用watch
File.Exists(Server.MapPath("Document")) //Returns false
,但是服务器具有相同的文件夹。
Please help me to solve this. 请帮我解决这个问题。
You need to transform the file name to a virtual form before using MapPath
. 使用
MapPath
之前,您需要将文件名转换为虚拟形式。 You must know the specifics of how it needs to be done. 您必须了解如何完成操作的细节。 For example:
例如:
string fileName = root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText;
fileName = fileName.Replace("..", "~");
if (File.Exists(Server.MapPath(fileName))
{
// you probably do not want MapPath here:
//proof.HRef = Server.MapPath(root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText);
proof.HRef = System.Web.VirtualPathUtility.ToAbsolute(fileName);
}
Try to print out Server.MapPath(root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText) it might be pointing a wrong path or something 尝试打印出Server.MapPath(root.GetElementsByTagName(“ FLD_DOC_ID”)[0] .InnerText),它可能指向错误的路径或其他内容
Any way, checking a file if it exists or not is very trivial: 无论如何,检查文件是否存在非常简单:
if(File.Exists(the file path))
{
}
First you have to get filepath (filename) from database using select query then use that path with file.exists. 首先,您必须使用选择查询从数据库中获取文件路径(文件名),然后将该路径与file.exists一起使用。
Example: 例:
First get filename or filepath from database then, 首先从数据库获取文件名或文件路径,然后,
if you get only filename then use below code: 如果仅获取文件名,则使用以下代码:
if(File.Exits(Server.MapPath("Document/5292013/"+filename)))
{
}
or if you get only filepath then use below code: 或者,如果仅获得文件路径,则使用以下代码:
if(File.Exits(Server.MapPath("filename")))
{
}
Thanks 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.