Search code examples
c#configurationweb-configconfiguration-files

How can I properly reference this config file so I'm not hard coding the path?


Im trying to reference this config file that is in the same folder as the class that contains this code. I'd like to do some type of relative reference to it, so I can use it from other places. When I try using just the file name without the path, the application doesn't find the file. I debugged and the folder it seems to be looking in IIS folder which makes sense as Im using it in an IIS hosted wcf service. Anyways, how I can properly reference this config file without hard coding the path? So it looks in the project location. Thanks for any help. Have a great weekend!

 public void Init()
    {
        var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = @"C:\workspace\new\UnityDemo-v1.0.0.1\src\Core\unity.config" };

        Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
        var unitySection = (UnityConfigurationSection)configuration.GetSection("unity");
        _container = new UnityContainer().LoadConfiguration(unitySection);
    }

Cheers,
~ck


Solution

  • Using config files with services hosted in IIS is tricky, because the application directory is the one IIS runs in and that will be heavily protected against placing any files there. There may be other ways but for me it works to name the file web.config and copy it to the directory the .svc file resides in and then you can read the settings directly without having to reference the config file. I do not know of any way to do this copying from within the program itself. The installer will be able to do it though. See: this question