CustomerName是从数据库值填充的字符串。检查文件名并在文件路径中使用它?
我想检查一个文件是否与该特定名称存在于一个目录中,如果存在,则将其用作文件路径。例如:
CustomerName = "James Doe"
假设它存在于images
文件夹,我想它存储在一个变量:
string filepath = HttpContext.Current.Server.MapPath("~\\images\\James Doe.png);
CustomerName是从数据库值填充的字符串。检查文件名并在文件路径中使用它?
我想检查一个文件是否与该特定名称存在于一个目录中,如果存在,则将其用作文件路径。例如:
CustomerName = "James Doe"
假设它存在于images
文件夹,我想它存储在一个变量:
string filepath = HttpContext.Current.Server.MapPath("~\\images\\James Doe.png);
如果你愿意,你需要使用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-26 21:01:58
可以使用File.Exists方法来检查它。
string filePath = httpContext.Current.Server.MapPath(string.Format(@"~\images\{0}.png", CustomerName);
if (File.Exists(filePath)
{
do.something()
}
谢谢你的代码warrior..but问题是文件格式可能会有所不同。它可以是一个jpeg文件或PNG或JPG格式...我怎么才能得到的路径然后.. – user1329614 2013-02-26 19:31:54
试试这个:
string filepath = Server.MapPath("~\\images\\" + CustomerName +".png");
if (File.Exists(filePath))
{
//do sth
}
谢谢阿德里安..但问题是文件格式可能vary.it可以是JPEG文件或PNG或JPG格式。 ..我怎么能得到路径然后 – user1329614 2013-02-26 19:32:26
检查:http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx – 2013-02-26 18:29:04