Rie*_*ies 27 .net c# app-config path
是否可以将整个App.Config文件重定位到自定义路径?
配置文件与exe文件位于同一文件夹中似乎有点奇怪,Windows的新approcah将所有程序设置保存在c:\ ProgramData和all中.
我们的另一个要求是以编程方式指定在哪里找到app.config文件.这样做的原因是我们从同一个exes生成不同的服务实例,并希望将每个服务的app.config存储在c:\ ProgramData \\下该服务的settings文件夹中.
小智 38
如果仍然相关,我们在Stack Overflow上使用了以下我在另一个问题的另一个建议答案中找到的...
AppDomain.CurrentDomain.SetData ("APP_CONFIG_FILE", "path to config file")
Run Code Online (Sandbox Code Playgroud)
当我们从DLL加载app.config时遇到问题时,我们工作得很好...
mYs*_*sZa 16
每个AppDomain都有/可以拥有自己的配置文件.CLR主机创建的默认AppDomain使用programname.exe.config; 如果要提供自己的配置文件,请创建单独的AppDomain.例:
// get the name of the assembly
string exeAssembly = Assembly.GetEntryAssembly().FullName;
// setup - there you put the path to the config file
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = System.Environment.CurrentDirectory;
setup.ConfigurationFile = "<path to your config file>";
// create the app domain
AppDomain appDomain = AppDomain.CreateDomain("My AppDomain", null, setup);
// create proxy used to call the startup method
YourStartupClass proxy = (YourStartupClass)appDomain.CreateInstanceAndUnwrap(
exeAssembly, typeof(YourStartupClass).FullName);
// call the startup method - something like alternative main()
proxy.StartupMethod();
// in the end, unload the domain
AppDomain.Unload(appDomain);
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
这对我有用..(摘自http://msdn.microsoft.com/en-us/library/system.configuration.appsettingssection.aspx)
// open config
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// update appconfig file path
config.AppSettings.File = "C:\\dev\\App.config";
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload in memory of the changed section.
ConfigurationManager.RefreshSection("appSettings");
Run Code Online (Sandbox Code Playgroud)
然后当你打电话
NameValueCollection settings = System.Configuration.ConfigurationManager.AppSettings;
Run Code Online (Sandbox Code Playgroud)
或任何获取应用程序配置的操作,都使用新路径.
希望这可能会帮助其他有同样问题的人!
我知道这是一个老问题,但对于那些谁只是希望有自己不同的位置,然后他们的二进制输出生成位置的app.config,下面的作品如微软预期它(因此,无需重新读取和重新写入文件到磁盘)
在运行时,配置文件中的设置将覆盖app.config中的设置(如果存在)。您完成了。
示例app.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<appSettings file="..\Config\settings.config">
<add key="port" value="1001"/>
</appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)
注意file =“ .. \ Config \ settings.config”。您完全可以自由定义要用户更改设置的位置的路径。
实际配置文件示例
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="port" value="1234"/>
</appSettings>
Run Code Online (Sandbox Code Playgroud)
在运行时,该设置port的值将为1234。
更多信息,请参见msdn