Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# App.Config更改值_C#_App Config - Fatal编程技术网

C# App.Config更改值

C# App.Config更改值,c#,app-config,C#,App Config,这是我的App.Config 用这个代码,我做了改变 lang = "Russian"; private void Main_FormClosing(object sender, FormClosingEventArgs e) { System.Configuration.ConfigurationManager.AppSettings.Set("lang", lang); } 但这并没有改变。我做错了什么?您不能为此使用AppSettings静态对象。试试这个 string a

这是我的App.Config


用这个代码,我做了改变

lang = "Russian";
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
     System.Configuration.ConfigurationManager.AppSettings.Set("lang", lang);
}

但这并没有改变。我做错了什么?

您不能为此使用AppSettings静态对象。试试这个

string appPath = System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location);          
string configFile = System.IO.Path.Combine(appPath, "App.config");
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();         
configFileMap.ExeConfigFilename = configFile;          
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

config.AppSettings.Settings["YourThing"].Value = "New Value"; 
config.Save(); 

AppSettings.Set
不会保留对配置文件的更改。它只是在内存中改变它。如果在
System.Configuration.ConfigurationManager.AppSettings.Set(“lang”,lang)上放置断点,并为
System.Configuration.ConfigurationManager.AppSettings[0]
添加一个监视,当该行代码运行时,您将看到它从“英语”更改为“俄语”

以下代码(在控制台应用程序中使用)将保留更改

class Program
{
    static void Main(string[] args)
    {
        UpdateSetting("lang", "Russian");
    }

    private static void UpdateSetting(string key, string value)
    {
        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save();

        ConfigurationManager.RefreshSection("appSettings");
    }
}
来自此帖子:

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings["PortName"].Value = "com3";
config.Save(ConfigurationSaveMode.Minimal);
上面要注意的一个要点是,如果您是从调试器(在Visual Studio中)运行此程序,则每次生成时都会覆盖app.config文件。测试这一点的最佳方法是构建应用程序,然后导航到输出目录并从那里启动可执行文件。在输出目录中,您还会找到一个名为YourApplicationName.exe.config的文件,它是您的配置文件。在记事本中打开此文件,查看更改是否已保存

使用“ConfigurationUserLevel.None”时,当您在调试文件夹中单击nameyourapp.exe时,代码将正确运行
但是当你在VisualStdio上开发应用程序时,你就不能正常运行了!!因为“vshost.exe”正在运行

以下参数可解决此问题: “应用程序。可执行路径

试试这个:(在VS 2012桌面版Express中测试)

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings["PortName"].Value = "com3";
config.Save(ConfigurationSaveMode.Minimal);

对不起,我的英语不好。对于.NET 4.0控制台应用程序,这些都不适合我。因此,我对Kevn Aenmey的答案进行了如下修改,它起到了作用:

private static void UpdateSetting(string key, string value)
{
    Configuration configuration = ConfigurationManager.
        OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
    configuration.AppSettings.Settings[key].Value = value;
    configuration.Save();

    ConfigurationManager.RefreshSection("appSettings");
}

只有第一行是不同的,构建在实际执行的程序集上。

除了fenix2222的答案(对我有效)之外,我不得不将最后一行修改为:

config.Save(ConfigurationSaveMode.Modified);

如果没有此选项,新值仍将写入配置文件,但在调试时检索到旧值。

在WPF应用程序中对我有效:

string configPath = Path.Combine(System.Environment.CurrentDirectory, "YourApplication.exe");
Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
config.AppSettings.Settings["currentLanguage"].Value = "En";
config.Save();

谢谢你的回答。 对我来说很合适

另一个读取值并返回字符串的有用代码段:

public static string ReadSetting(string key)
    {
        System.Configuration.Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        System.Configuration.AppSettingsSection appSettings = (System.Configuration.AppSettingsSection)cfg.GetSection("appSettings");
        return appSettings.Settings[key].Value;

    }

要更新除
appsettings
之外的条目,只需使用
XmlDocument

public static void UpdateAppConfig(string tagName, string attributeName, string value)
{
    var doc = new XmlDocument();
    doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    var tags = doc.GetElementsByTagName(tagName);
    foreach (XmlNode item in tags)
    {
        var attribute = item.Attributes[attributeName];
        if (!ReferenceEquals(null, attribute))
            attribute.Value = value;
    }
    doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
这就是你所说的:

Utility.UpdateAppConfig("endpoint", "address", "http://localhost:19092/NotificationSvc/Notification.svc");

Utility.UpdateAppConfig("network", "host", "abc.com.au");

此方法也可以进行改进,以适应appSettings值

但它会重新启动。。。我在表单关闭时进行更改。。。当我再次运行程序时,没有任何变化,您是否得到任何异常?您正在使用WinForms吗?在使用Visual Studio 2013 Ultimate的.Net(4.5)上,我可以使用System.Configuration,但不能使用System.Configuration.Configuration等对象。设置值时,它会引发NullReferenceException。config.AppSettings.Settings计数为零,但我的AppSettings中有一个键。我在c#4上。5@TechJerk您使用的是app.config还是web.config?那么我如何进行更改?System.Configuration.ConfigurationManager.AppSettings[0]本身不会执行任何操作。。。请填写代码,以便我必须编写System.Configuration.ConfigurationManager.AppSettings[0]=lang?因为我复制了你的代码并在VS 2012 c#4.5上运行,所以它不起作用。我确实检查了bin/debug文件夹配置文件。它只在我添加“configFileMap”时起作用,如已接受回答中所示。要获得更健壮的代码,如果密钥已存在,则可以添加测试:
if(configuration.AppSettings.Settings[key]==null)configuration.AppSettings.Settings.add(key,value);else配置.AppSettings.Settings[key].Value=Value可能重复您可能不想在ConfigurationSaveMode.Full中保存配置。这会在你的app.config中添加大量你不想要的内容。其余的都很好。您可能还希望与调用
OpenExeConfiguration
应用程序.ExecutablePath
选项结合使用,如@Amin Ghaderi的answer@jned29如果我的答案对你有帮助的话,请随意投票。非常感谢。那太好了。