简体   繁体   中英

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

Use Application.StartupPath to get the path the application started in then simply combine with the filename to get the full path:

var filePath = Path.Combine(Application.StartupPath, "unity.config");
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath };

This will work only in winforms.


Another option is to use Environment.CurrentDirectory - by default it will be set to the process startup directory. Note that this property is mutable:

var filePath = Path.Combine(Environment.CurrentDirectory, "unity.config");
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath };

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

Another option that worked for me in .NET is using Server.MapPath . This returns the full path of the given relative virtual path in the web application.

var filePath = Server.MapPath("/unity.config")

This physical file path can then be used to create the file map as above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM