0

I use Bundle. But it not send exception if file not found.

I need check exist file and catch exception if file not exist. I tried:

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

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

but always had exception

How check exist file on global asax or in bundle settings?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Mediator
  • 14,951
  • 35
  • 113
  • 191
  • Well have you taken the path that `server.MapPath` generates and *actually* verified it exists? – Arran Apr 24 '13 at 12:07
  • Yes, it's I bad. need remove first '/'. But I would like to use bundle that he gave me excaption – Mediator Apr 24 '13 at 13:53

1 Answers1

1

I prefer to use a BundleHelper for this task.

Herman has an excellent one here: https://stackoverflow.com/a/25784663/732377

Copied here for completeness, but all the kudos should go to Herman!

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);
    }
}

Then in configuration:

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

However, you might also want to checkout other solutions to this common problem.

nrodic is pretty straight forward here: https://stackoverflow.com/a/24812225/732377

Community
  • 1
  • 1
Sam
  • 535
  • 5
  • 14