0

尝试将所有数据保存到配置文件中,然后在运行期间读取它并应用于我的程序 - 作为用户偏好。已完成:创建新的配置文件(使用添加新元素-> 添加 congif 文件)。在这个文件中放简单的代码

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSetting>
        <add Key="Volume" value="100" />
    </appSetting>
</configuration>

在它创建方法之后

public int GetVolumeFromConfigFile()
    {
        return  Convert.ToInt32(ConfigurationManager.AppSettings.Get("Volume"));
    }

并在主程序中调用它

Value = (MyClass.GetVolumeFromConfigFile());

但这是行不通的。(在 debaggin 期间它什么都不返回)

认为这可能是几个原因:

  1. 我需要添加(我现在不知道以什么方式)要使用的配置文件,因为我有几个文件 *.config - 一个作为默认文件(App.exe.config,另一个 - 我创建的)
  2. 我使用不正确的方法从配置文件中获取值

我还阅读了另一种存储应用程序设置的方法,例如将其存储在 *.settings 文件中我做错了什么以及首选哪种方法?

附加信息 - 使用 net 4.0

编辑

删除我的配置文件,并添加到现有的几行(在strong>中)

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="PlayDemo.SettingsPlayIt" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
       </sectionGroup>
    </configSections>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <userSettings>
        <PlayDemo.SettingsPlayIt>
            <setting name="Volume" serializeAs="String">
                <value>10</value>
            </setting>
        </PlayDemo.SettingsPlayIt>
    </userSettings>

在这里我添加我的密钥

    <appSetting>
        <add key="Volume" value="100" />
    </appSetting>

</configuration>
4

3 回答 3

3

尝试这个:

<?xml version="1.0" encoding="utf-8" ?>
   <configuration>
      <appSettings>
         <add key="Volume" value="100" />
      </appSettings>
   </configuration>

return  Convert.ToInt32(ConfigurationManager.AppSettings["Volume"]);

appSettings 是键值对,因此您可以像访问字典中的值一样访问它

于 2013-09-17T17:27:50.907 回答
1

如果你想使用单独的配置文件,试试这个:

Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
config.AppSettings.File = "yourFileName"'tell Configuration what file to read
config.Save(ConfigurationSaveMode.Modified) ' save the Configuration setting
ConfigurationManager.RefreshSection("appSettings") ' update just the <appSettings> node
于 2013-09-17T17:54:07.783 回答
0

我真的很喜欢以下技术,使用ConfigurationSection. 这使您可以轻松地操作您的配置。但它是更具体的前期。

http://msdn.microsoft.com/en-us/library/2tw134k3%28v=vs.90%29.aspx

于 2013-09-19T21:16:23.790 回答