日期:2014-05-16  浏览次数:20820 次

关于Configuration
见到鬼了,在VS2012下:麻烦各位帮我看一下,这里有清楚的步骤

1. File | New | Console Project
2. Add | New Item | Settings File | name it as "MySettings.settings"
3. 在那个灰色的Setting文件的界面里,把 "name" 改为 "MyName", 初始值写 "MyNameValue"
4.  Add reference: System.Configuration, and in Program.cs, add : using System.Configuration;
5.  add code as:
        static void Main(string[] args)
        {
            MySettings ms = new MySettings();
            Console.WriteLine(ms.MyName);
            ms.MyName = "I change it" + DateTime.Now;
            Console.WriteLine(ms.MyName);
            Console.WriteLine("Use AppSetting to read setting : " + ConfigurationManager.AppSettings["MyName"] +  " is blank?");
            ms.Save();
            Console.ReadLine();
        }

我的问题是:
一,小问题:ConfigurationManager.AppSettings["MyName"]总是返回空

二,大问题:运行这个程序后,MyName的值会给更改和保存,你重新运行程序时,它
记住上次被更改的值,问题是,它到底保存在什么地方了?app.config没有
{AppName}.exe.config里也没有,{AppName}.exe.vshost.config也还是没有

如果你把这个EXE程序复制到任何子目录里,没有任何config文件,它仍然得到初始
的值,并且,也能保存你修改后的值,它到底把值放哪儿了?



------解决方案--------------------
问题一:
ConfigurationManager.AppSetting是另外一个概念,它用的是app.config中的<appSettings>部分,比如:

<configuration>
  <appSettings>
    <add key="AppMy" value="AppMyValue" />
  </appSettings>
</configuration>

而你的MyName配置,则在<userSetting>结点下。

问题二:
你的MyName使用的是'用户级别(user-scroped)'的配置。注意设计器提供了‘用户’,和‘应用’两种级别。
而用户级别的配置,一般存在用户的文件夹下。

如果是win7,一般在C:\Users\当前用户名\AppData\Local\Microsoft\程序名字\版本号\user.config
其中的'Microsoft'是你程序的AssemblyCompany特性,如果没有设置就默认为Microsoft。

如果是XP,一般在C:\Documents and Settings\当前用户名\Local Settings\Application Data里面找。