我正在努力将自定义部分保存到app.config中。 这是我目前的代码:
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//Read the TunnelSection from the configuration file
TunnelSection tunnels = ConfigurationManager.GetSection("TunnelSection") as TunnelSection;
HostConfigElement newhost = new HostConfigElement();
newhost.Password = "hola";
newhost.SSHPort = 22;
newhost.SSHServerHostname = "holahola";
TunnelConfigElement newtunnel = new TunnelConfigElement();
newtunnel.LocalPort = 12;
newtunnel.RemotePort = 12;
newtunnel.Name = "12";
newtunnel.DestinationServer = "12";
TunnelCollection newtunnelcollection = new TunnelCollection();
newtunnelcollection.Add(newtunnel);
newhost.Tunnels = newtunnelcollection;
tunnels.Tunnels.Add(newhost);
ConfigurationManager.RefreshSection("TunnelSection");
configuration.Save(ConfigurationSaveMode.Full);
问题在于配置文件没有被修改。如果我循环遍历TunnelSection,我会看到新的主机已经被添加了。
为了排除权限问题,我尝试像这样向appsettings中添加一个设置:
configuration.AppSettings.Settings.Add("hola", "hola");
这个方法很有效。
我也尝试了saveas,但没有成功。
有什么想法吗? 谢谢提供帮助!