代码之家  ›  专栏  ›  技术社区  ›  Omar

截取所有相对路径

  •  2
  • Omar  · 技术社区  · 15 年前

    在计算绝对路径之前,是否可以截取应用程序中使用的所有和任何相对路径,并删除/编辑其中的一部分?

    例子:

    在mvc视图页面中-

    <%= Html.Image("~/{somefolder}/logo.png") %>
    

    我想截取相对路径“~/{somefolder}/logo.png”,并将“{somefolder}”替换为通过某种逻辑(数据库、if/else等)检索到的文件夹位置

    1 回复  |  直到 15 年前
        1
  •  2
  •   Dan Atkinson    15 年前

    您可以创建一个这样做的帮助器。

    例如

    public static string LinkedImage(this HtmlHelper html, string url)
    {
      Regex regex = new Regex("({(.*?)})");//This is off the top of my head regex which will get strings between the curly brackets/chicken lips/whatever! :).
      var matches = regex.Matches(url);
    
      foreach (var match in matches)
      {
        //Go get your value from the db or elsewhere
        string newValueFromElsewhere = GetMyValue(match);
        url = url.Replace(string.Format("{{0}}", match), newValueFromElsewhere);
      }
    
      return html.Image(url);
    }
    

    here 在斯蒂芬·沃尔特的博客上。