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

标签 c# asp.net regex file-io

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

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/

相关文章:

java - 使用正则表达式解析字符串

java - 替换java中的某些字符

python - 用生成的图像替换 xml 标签(python 正则表达式)

c# - 如何使用azure sdk获取虚拟机公共(public)IP?

c# - .ToString()、(字符串)或作为字符串。什么时候用什么?

c# - Microsoft Graph API - 以其他用户身份发送电子邮件

c# - 列表数据结构C#效率

c# - Page_Init 方法异常中的 DotNetNuke 重定向

c# - 由于母版页中的 updatepanel,内容页中的 asp FileUpload 无法工作

c# - C#查看邮件状态是否送达