C# 读取,删除,增加,修改app.config配置文件信息

C# 读取,删除,增加,修改app.config配置文件信息

string file = Application.ExecutablePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
config.AppSettings.Settings.Add("test", "1");
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

多次添加结果:

<configuration>
    <appSettings>
        <add key="test" value="1,1,1" />
    </appSettings>
</configuration>

 2018-03-01 17:10  罗分明网络博客  C#基础  3627  0

20180509更新,新增 --添加,修改,删除功能

以下是  app.config文件里面代码

1

2

3

4

5

6

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <appSettings>

    <add key="lqwvje" value="罗分明"/>

  </appSettings>

</configuration>

以下是读取配置文件信息方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

/// <summary>

/// 修改和添加AppSettings中配置 如果相应的Key存在则修改 如不存在则添加

/// </summary>

/// <param name="key">key值</param>

/// <param name="value">相应值</param>

public static bool SetConfigValue(string key, string value)

{//转载请保留 http://www.luofenming.com/show.aspx?id=ART2018030100002

    try

    {

        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        if (config.AppSettings.Settings[key] != null)

        {

            config.AppSettings.Settings[key].Value = value;

        }

        else

        {

            config.AppSettings.Settings.Add(key, value);

        }

 

        config.Save(ConfigurationSaveMode.Modified);

        ConfigurationManager.RefreshSection("appSettings");

        return true;

    }

    catch

    {

        return false;

    }

}

 

/// <summary>

/// 删除

/// </summary>

/// <param name="keyName"></param>

public void removeItem(string keyName)

{

    //删除配置文件键为keyName的项 

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    config.AppSettings.Settings.Remove(keyName);

    config.Save(ConfigurationSaveMode.Modified);

    ConfigurationManager.RefreshSection("appSettings");

}

 

/// <summary>

/// 查看相应Key的Value

/// </summary>

/// <param name="keyName"></param>

/// <returns></returns>

public string valueItem(string keyName)

{

    //返回配置文件中键为keyName的项的值 

    return ConfigurationManager.AppSettings[keyName];

}

注意:修改和删除不是在APP.Config里面修改,改是复制在另外一个文件里面如下图

posted @ 2020-01-04 09:03  grj001  阅读(536)  评论(0编辑  收藏  举报