2013-02-26 87 views
1

CustomerName是从数据库值填充的字符串。检查文件名并在文件路径中使用它?

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

CustomerName = "James Doe" 

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

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

检查:http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx – 2013-02-26 18:29:04

回答

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. 
} 
+0

你是非常欢迎。 – 2013-02-26 21:01:58

2

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

string filePath = httpContext.Current.Server.MapPath(string.Format(@"~\images\{0}.png", CustomerName); 
if (File.Exists(filePath) 
{ 
    do.something() 
} 
+0

谢谢你的代码warrior..but问题是文件格式可能会有所不同。它可以是一个jpeg文件或PNG或JPG格式...我怎么才能得到的路径然后.. – user1329614 2013-02-26 19:31:54

0

试试这个:

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

谢谢阿德里安..但问题是文件格式可能vary.it可以是JPEG文件或PNG或JPG格式。 ..我怎么能得到路径然后 – user1329614 2013-02-26 19:32:26