使用正则表达式引用一组文件路径

本文关键字:一组 文件 路径 正则表达式 引用 | 更新日期: 2023-09-27 18:23:46

我可以用正则表达式对磁盘进行一次读取而不是三次吗?

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,您会找到一个。

尝试这样的操作(仅适用于.NET4及以后版本):

string folder = HttpContext.Current.Server.MapPath("~/Assets/Images/");
string[] extensions = { ".jpg", ".gif", ".png" };
bool exists = Directory.EnumerateFiles(folder, "*.*", SearchOption.TopDirectoryOnly)
                 .Any(f => extensions.Contains(Path.GetExtension(f)));

您可以获得目录位置中所有文件的列表,并使用LINQ查找路径,使用Directory.EnumerateFiles:

var files = Directory.EnumerateFiles(Server.MapPath("~/Assets/Images/"));
if(files.Contains(string.Format("{0}.png", id))
{
}

根据文件的数量,它可能会产生比您的解决方案更好的结果。

这更像是对@Oded想法的修改,但我可能会做这样的事情:

var extensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)  
    {  ".png", ".gif", ".jpg", ".bmp" };
var firstMatchingPath = Directory.EnumerateFiles(Server.MapPath("~/Assets/Images/"))
     .Where(s => extensions.Contains(Path.GetExtension(s))
     .FirstOrDefault();

这对你有用吗?它使用正则表达式并保持匹配的优先级

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;

有很多不错的答案,但我选择了这种结合了几个的方法。

var path = Directory.EnumerateFiles(HttpContext.Current.Server.MapPath("~/Assets/Images/"), string.Format("{0}.*", id), SearchOption.TopDirectoryOnly).FirstOrDefault();
switch (Path.GetExtension(path))
{
    case ".png":
    case ".jpg":
    case ".gif":
        break;
    default:
        return;
}