views:

519

answers:

2

I have an asp.net mvc project that uses some search methods in a seperate library. This library needs to know the location of my lucene index files.

    private static string lucenePath = ConfigurationManager.AppSettings["lucenePath"];

    public static ColorList SearchColors(Query query) {
        return new ColorList(
            new IndexSearcher(Path.GetFullPath(lucenePath)),
            query);
    }

This correctly reads my configured lucenePath from the web.config's application key node. But how can I get the correct full path from this relative path? Path.GetFullPath gives me a completely incorrect path.

--Conclusion--
If you want to go full-out, tvanfosson's answer is probably for you.
I, however, kept it a little more brain dead by using the following:

Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
    ConfigurationManager.AppSettings["luceneIndex"].TrimStart('\\'));

This will look in the caller's app.config for an appkey called "path" and combine its value to the caller's path. The TrimStart() makes sure that the config file can both contain a leading \ or not.

+1  A: 
Server.MapPath(string);
abatishchev
The library should be usable both from the website as from any other application. It should really just take the current running path, apply the relative path and return the result.
borisCallens
Hmm.. maybe something from http://stackoverflow.com/questions/362790/what-is-the-best-way-to-determine-application-root-directory would help
abatishchev
A: 

Since you are referencing this from a separate library, you might have to jump through a bunch of hoops to get access to the HttpServerUtitity or introduce some coupling to classes that are difficult to mock. You might want to consider having a single configuration class that loads properties from the web configuration that gets injected into your library via constructor/setter. To make it easier to test against, you could define an interface that could be mocked in your unit tests and have it implement that. The configuration class could use the HttpServerUtility to obtain the absolute path and store it internally to be reused.

tvanfosson
Is there no way of completely removing the dependency on HttpServerUtility? This library should be consumable from a non-web app too... It feels weird to include a system.web lib in a standalone application. Not?
borisCallens
Sure -- implement two versions of the configuration class implementing the interface. The one running from the web site lives in the web code and uses HttpServerUtility to find the path. The one running from your standalone app can use the current executing assembly to get the executable's path.
tvanfosson
Both can derive from a common base class that implements most of the logic (using ConfigurationManager, not WebConfigurationManager) to keep your code DRY.
tvanfosson