CustomerName 是从数据库值填充的字符串。
我想检查目录中是否存在具有该特定名称的文件,如果存在,则将其用作文件路径。例如:
CustomerName = "James Doe"
假设它存在于images
文件夹中,我想将它存储在一个变量中:
string filepath = HttpContext.Current.Server.MapPath("~\\images\\James Doe.png);
您可以使用 File.Exists 方法来检查它。
string filePath = httpContext.Current.Server.MapPath(string.Format(@"~\images\{0}.png", CustomerName);
if (File.Exists(filePath)
{
do.something()
}
如果您希望能够使用通配符(例如,如果文件扩展名未知),则需要使用System.IO.Directory.GetFiles
.
string path = HttpContext.Current.Server.MapPath("~\\images");
string filePattern = String.Format("{0}.*", CustomerName);
string[] files = System.IO.Directory.GetFiles(path, filePattern);
if (files.Length > 0)
{
//here you can check which file(s) was returned and the corresponding extension.
}
尝试这个:
string filepath = Server.MapPath("~\\images\\" + CustomerName +".png");
if (File.Exists(filePath))
{
//do sth
}