views:

112

answers:

2

Is there a way to find the name (and path) of the current application's config file from inside a class library?

E.g. in a web app this would be web.config, in a windows app or service this would be myapp.exe.config.

+3  A: 

Try this:

AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

If that doesn't work, add references to System.Web and System.Configuration, then try this:

if(HttpRuntime.AppDomainAppVirtualPath  == null) 
    return ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath;
else
    return VirtualPathUtility.ToAbsolute("~/Web.config");
SLaks
Thanks. After a first test, the first approach seems to work for windows services and web apps.
M4N
@SLaks: I never accept answers immediately (but I will do), e.g. to be able to verify the solution and to give others a chance to answer.
M4N
A: 

Use Configuration.FilePath:

Gets the physical path to the configuration file represented by this Configuration object.

Andrew Hare
Yeah, but then you need to have a "Configuration" element first... there's unfortunately no "Configuration.CurrentElement" or anything like that...
marc_s
How would I get to an instance of Configuration?
M4N