C# 检查文件名并在文件路径中使用它?

C# 检查文件名并在文件路径中使用它?,c#,asp.net,file,C#,Asp.net,File,CustomerName是从数据库值填充的字符串 我想检查目录中是否存在具有该特定名称的文件,如果存在,则将其用作文件路径。例如: CustomerName = "James Doe" 假设它存在于images文件夹中,我想将其存储在一个变量中: string filepath = HttpContext.Current.Server.MapPath("~\\images\\James Doe.png); 您可以使用File.Exists方法来检查它 string filePath = ht

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()
}
试试这个:

string filepath = Server.MapPath("~\\images\\" + CustomerName +".png");
if (File.Exists(filePath))
{
//do sth
}

如果希望使用通配符(例如,如果文件扩展名未知),则需要使用
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.
}

谢谢你的代码战士..但问题是文件格式可能会有所不同。它可以是jpeg文件或png或jpg…那么我如何获取路径..谢谢你Adrian..但问题是文件格式可能会有所不同。它可以是jpeg文件或png或jpg…那么我如何获取路径呢