0

我使用捆绑包。但如果找不到文件,它不会发送异常。

如果文件不存在,我需要检查存在的文件并捕获异常。我试过了:

var cssCommon = "/Common/common.css";

if (!System.IO.File.Exists(server.MapPath("~") + cssCommon))
{
   throw new FileNotFoundException(cssCommon);
}

但总是有例外

如何检查全局 asax 或捆绑设置中的现有文件?

4

1 回答 1

1

我更喜欢使用 aBundleHelper来完成这项任务。

赫尔曼在这里有一个很好的:https ://stackoverflow.com/a/25784663/732377

为了完整起见,复制到这里,但所有的荣誉都应该归功于赫尔曼!

public static class BundleHelper
{
    [Conditional("DEBUG")] // remove this attribute to validate bundles in production too
    private static void CheckExistence(string virtualPath)
    {
        int i = virtualPath.LastIndexOf('/');
        string path = HostingEnvironment.MapPath(virtualPath.Substring(0, i));
        string fileName = virtualPath.Substring(i + 1);

        bool found = Directory.Exists(path);

        if (found)
        {
            if (fileName.Contains("{version}"))
            {
                var re = new Regex(fileName.Replace(".", @"\.").Replace("{version}", @"(\d+(?:\.\d+){1,3})"));
                fileName = fileName.Replace("{version}", "*");
                found = Directory.EnumerateFiles(path, fileName).Where(file => re.IsMatch(file)).FirstOrDefault() != null;
            }
            else // fileName may contain '*'
                found = Directory.EnumerateFiles(path, fileName).FirstOrDefault() != null;
        }

        if (!found)
            throw new ApplicationException(String.Format("Bundle resource '{0}' not found", virtualPath));
    }

    public static Bundle IncludeExisting(this Bundle bundle, params string[] virtualPaths)
    {
        foreach (string virtualPath in virtualPaths)
            CheckExistence(virtualPath);

        return bundle.Include(virtualPaths);
    }

    public static Bundle IncludeExisting(this Bundle bundle, string virtualPath, params IItemTransform[] transforms)
    {
        CheckExistence(virtualPath);
        return bundle.Include(virtualPath, transforms);
    }
}

然后在配置中:

 bundles.Add(new ScriptBundle("~/test")
    .IncludeExisting("~/Scripts/jquery/jquery-{version}.js")
    .IncludeExisting("~/Scripts/lib*")
    .IncludeExisting("~/Scripts/model.js")
    );

但是,您可能还想查看此常见问题的其他解决方案。

nrodic 在这里非常简单:https ://stackoverflow.com/a/24812225/732377

于 2015-01-23T10:46:20.063 回答