我可以使用正则表达式读取磁盘一次而不是读取三次吗?
var path = HttpContext.Current.Server.MapPath(string.Format("~/Assets/Images/{0}.png", id));
if (!File.Exists(path))
{
path = HttpContext.Current.Server.MapPath(string.Format("~/Assets/Images/{0}.jpg", id));
if (!File.Exists(path))
{
path = HttpContext.Current.Server.MapPath(string.Format("~/Assets/Images/{0}.gif", id));
最佳答案
假设你不关心你击中了哪个:
using System.IO
string imagesPath = HttpContext.Current.Server.MapPath("~/Assets/Images");
string path = null;
foreach (var filePath in Directory.GetFiles(imagesPath, id + ".*"))
{
switch (Path.GetExtension(filePath))
{
case ".png":
case ".jpg":
case ".gif":
path = filePath;
break;
}
}
如果 path
不是 null
你找到了。
关于c# - 使用正则表达式引用一组文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17733436/