1

CustomerName 是从数据库值填充的字符串。

我想检查目录中是否存在具有该特定名称的文件,如果存在,则将其用作文件路径。例如:

CustomerName = "James Doe"

假设它存在于images文件夹中,我想将它存储在一个变量中:

string filepath = HttpContext.Current.Server.MapPath("~\\images\\James Doe.png);
4

3 回答 3

2

您可以使用 File.Exists 方法来检查它。

string filePath = httpContext.Current.Server.MapPath(string.Format(@"~\images\{0}.png", CustomerName);
if (File.Exists(filePath)
{
    do.something()
}
于 2013-02-26T18:31:01.550 回答
1

如果您希望能够使用通配符(例如,如果文件扩展名未知),则需要使用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.
}
于 2013-02-26T20:13:52.990 回答
0

尝试这个:

string filepath = Server.MapPath("~\\images\\" + CustomerName +".png");
if (File.Exists(filePath))
{
//do sth
}
于 2013-02-26T18:35:43.513 回答