Mediator
Mediator

Reputation: 15378

How to check exist file in global asax or bundles?

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?

Upvotes: 0

Views: 1525

Answers (1)

Sam
Sam

Reputation: 603

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

Upvotes: 1

Related Questions