My App.Config file isn't saving anything I modify

喜夏-厌秋 提交于 2019-12-10 11:54:46

问题


Here's my code:

public void VerifyIfFirstTimeRun()
    {
        if (System.Configuration.ConfigurationSettings.AppSettings["FirstTimeRunning"] == "true")
        {
            //Do bla bla bla
            //Then do bla bla bla
            System.Configuration.ConfigurationSettings.AppSettings["FirstTimeRunning"] = "false";     
        }            
    }

Problem is, I'm testing this with the F5 key, it boots up and sure enough using a breakpoint shows that it is indeed going inside the If Condition, but when I "Stop" the application and press F5 again it goes inside the If Condition AGAIN. Is this standard operational procedures?

If so, how can I test if its working?


回答1:


This is going against the spirit of what the App.config file is used for ... but to answer your question, you need to do System.Configuration.Configuration.Save().

Edit:
App.config is typically used to configure database connections, providers, etc. And is usually set once at installation. It's suggested that user settings go into a separate config file user.config. See this for the explanation.

Edit:
System.Configuration.Configuration class.

Note - now that I read why you're using these settings, may I suggest another way? You should probably just check if the file is there:

if (!File.Exists("thefilepath"))
{
    AlertUserOfMissingFile();
    ChooseNewFile();
}

It's safer this way anyhow because having a setting set to true doesn't necessarily mean the file is where you think it is.




回答2:


I'm not sure you should expect this to save; you can, however, have a settings file that has a setting (a bool in this case) in the user's context, which saves (when you ask it to) via Settings.Default.Save().




回答3:


I don't advice you to use App.settings for this purpose. Take a look a this article Settings in C#

  1. In Solution Explorer, expand the Properties node of your project.
  2. In Solution Explorer, double-click the .settings file in which you want to add a new setting. The default name for this file is Settings.settings.
  3. In the Settings designer, set the Name, Type, Scope, and Value for your setting. Each row represents a single setting. Figure 1 shows an example of the Settings designer.

If you want to persist changes to user settings between application sessions, call the Save method, as shown in the following code:

Properties.Settings.Default.Save();


来源:https://stackoverflow.com/questions/1282748/my-app-config-file-isnt-saving-anything-i-modify

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!