这是代码:
// These is works
Console.WriteLine(Properties.Settings.Default.name);
Configuration configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
KeyValueConfigurationCollection settings = configFile.AppSettings.Settings;
settings.Add("Port", "12");
// Here it fails
configFile.Save(ConfigurationSaveMode.Modified);
app.config文件的内容:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="ConsoleApplication1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false"/>
</sectionGroup>
</configSections>
<userSettings>
<ConsoleApplication1.Properties.Settings>
<setting name="name" serializeAs="String">
<value>dasdqweqw</value>
</setting>
</ConsoleApplication1.Properties.Settings>
</userSettings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/></startup></configuration>
无法理解为什么它不起作用。代码是对的还是我做错了什么?在线configFile.Save(ConfigurationSaveMode.Modified);它会抛出异常&#34;在锁定时无法编辑ConfigurationSection属性。&#34;
我决定遵循什么情况: 1.通过解决方案资源管理器我打开项目属性页面(解决方案资源管理器&gt;项目节点的上下文菜单&gt;属性),然后通过项目属性页面中的设置选项卡创建项目的应用程序设置(范围参数的值是用户)。这将在项目的名称空间中创建Properties类(位于Settings.Designer.cs文件中)。相应的类属性。 https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2008/cftf714c%28v=vs.90%29 2.要创建用户特定的user.config文件,我必须更改添加的设置&amp;调用Properties.Settings.Default.Save()方法。如果我只调用Properties.Settings.Default.Save()而不更改设置,则不会创建user.config文件。
用法例子:
Properties.Settings.Default.updateTime = DateTime.UtcNow;
Properties.Settings.Default.Save();
Console.WriteLine((Properties.Settings.Default.updateTime - DateTime.UtcNow).Hours);
Console.ReadLine();
user.config的内容:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<userSettings>
<coonfoo.Properties.Settings>
<setting name="updateTime" serializeAs="String">
<value>06/03/2018 10:42:03</value>
</setting>
</coonfoo.Properties.Settings>
</userSettings>
</configuration>
答案 0 :(得分:0)
这应该有用。
class Program
{
static void Main(string[] args)
{
Configuration roaming = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = roaming.FilePath;
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
KeyValueConfigurationCollection settings = configuration.AppSettings.Settings;
settings.Add("Port", "12");
configuration.Save(ConfigurationSaveMode.Modified);
}
}
找到this可能对您有帮助。