我正在尝试在我的项目中使用 settings.settings 文件。有些值需要在 .exe 文件和各种 DLL 之间共享。我不想只是传递这些值,我想在需要时访问它们,但每个项目设置其值的名称略有不同,因此其他项目无法访问它们。
有没有办法使用 settings.settings 方法在 .exe 和 .dll 之间共享 app.config 文件的内容?还是我需要返回使用 ConfigurationManager 才能执行此操作?
最佳答案
只需将您的设置放在 App.config 文件中,然后从您的 dll 中读取它们。事实上,我相信这是你的 dll 唯一会寻找设置/配置的地方,dll 的本地配置将被忽略。
这里有一个简单的例子来确保 dll 没有对应用程序的强引用。这段代码不是很好,但你明白了。
private string GetSettingValue(string key)
{
string executingAssembly = Assembly.GetEntryAssembly().GetName().Name;
string sectionName = "applicationSettings/" + executingAssembly
+ ".Properties.Settings";
ClientSettingsSection section =
(ClientSettingsSection)ConfigurationManager.GetSection(sectionName);
// add null checking etc
SettingElement setting = section.Settings.Get(key);
return setting.Value.ValueXml.InnerText;
}
或者有一个带有共享设置的公共(public) dll
,并从需要共享配置的每个程序集中获取依赖项。这要干净得多。
关于c# - .exe 和 .dll 之间的共享配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7336215/