这对你有用吗?它使用正则表达式并保持匹配的优先级
var folderPath = HttpContext.Current.Server.MapPath(string.Format("~/Assets/Images"));
var regex = new Regex(string.Format("{0}[.](png|jpg|gif)", id));
var fileInfo = new DirectoryInfo(folderPath)
.GetFiles()
.Where(w => regex.Match(w.Name).Success)
.OrderByDescending(o => o.Extension)
// Taking advantage of png jpg gif is reverse alphabetical order,
// take .OrderByDecending() out if you don't care which one gets found first
.FirstOrDefault();
var path = fileInfo != default(FileInfo) ? fileInfo.FullName : string.Empty;
如果我把它缩小一点(2 个陈述)
var fileInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath(string.Format("~/Assets/Images")))
.GetFiles()
.Where(w => Regex.Match(w.Name, string.Format("{0}[.](png|jpg|gif)", id)).Success)
.OrderByDescending(o => o.Extension)
.FirstOrDefault();
var path = fileInfo != default(FileInfo) ? fileInfo.FullName : string.Empty;