从C#应用程序中的配置文件中检索值不起作用 [英] Retrieving Value from Config file in C# Application Doesn't Work

查看:49
本文介绍了从C#应用程序中的配置文件中检索值不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个问题,当我尝试使用配置文件
时,我在这里和其他地方看到了一些帖子
,但我无法解决工作中的问题

I'm having an issue, when I'm trying to work with a config file, I've read a few posts here and somewhere else but I can't solve problem in work,

在这里的问题中,我已经添加了配置。

In my question here, I have added the Configuration.

<?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="CA.Properties.Settings" 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>
        <CA.Properties.Settings>
 
          <appSettings>
            <add key="ab123" value="D:\ab123\Source\ab123.c" />
          </appSettings>

        </CA.Properties.Settings>
    </userSettings>
</configuration>

在文档中声明

string ab123 = ConfigurationManager.AppSettings["ab123"];

但在侧面,我显示错误是
未处理win32异常-系统找不到指定的文件

But in the side , I show error is " win32 Exception was unhandled - System can not find the file specified"

System.Diagnostics.Process.Start(ConfigurationManager.AppSettings["ab123"]);

运行此代码时, ab123 的值始终为空!
我确定路径是正常的。

When I run this code, ab123 value is always null! I'm sure the path is normal.

我该如何解决?

推荐答案

从您的xml配置文件中可以看出,您实际上是在尝试使用用户设置而不是应用程序设置,并且您已经混淆了一些想法。我认为配置的更正确版本可能是:

It appears from your xml config files that you are really trying to use User Settings rather than Application setting and that you have mixed some of the ideas up. I think a more correct version of a config might be:

<?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="CA.Properties.Settings" 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>
      <CA.Properties.Settings>
        <setting name="ab123" serializeAs="String">
          <value>D:\ab123\Source\ab123.c</value>
        </setting>
        </CA.Properties.Settings>
    </userSettings>
</configuration>

唯一的区别是定义设置的方式。例如,我将其更改为:

The only significant difference is the way you define settings. For example I changed it to:

<setting name="ab123" serializeAs="String">
    <value>D:\ab123\Source\ab123.c</value>
</setting>

您可以使用其他名称

客户端代码有点不同,因为它必须找到userSettings,找到程序属性设置,然后查询密钥(例如 ab123 )。我添加了一些琐碎的错误处理,但是您需要自己处理错误。我只是返回错误以简化代码。该代码具有内联注释,可帮助您了解发生了什么情况。

The client code is a bit different as it has to find the userSettings, find the program property settings and then query for the key (like ab123). I have added some trivial error handling but you need to deal with the errors yourself. I simply return on error for code simplification. The code has inline comments to help figure out what is going on.

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Diagnostics;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            // Retrieve the userSettings gorup
            ConfigurationSectionGroup group = config.SectionGroups[@"userSettings"];
            if (group == null) return;

            // Get the program settings
            ClientSettingsSection clientSection = group.Sections["CA.Properties.Settings"] as ClientSettingsSection;
            if (clientSection == null) return;

            // This retrieves the value associated with the key
            string sFileName = clientSection.Settings.Get("ab123").Value.ValueXml.InnerText;

            // Check if ab123 has a value and the file exists
            if (!string.IsNullOrEmpty(sFileName) && System.IO.File.Exists(sFileName))
            {
                using (StreamReader sr = new StreamReader(sFileName))
                {
                    string line;
                    // Read and display lines from the file until the end of  
                    // the file is reached. 
                    while ((line = sr.ReadLine()) != null)
                    {
                        System.Diagnostics.Debug.WriteLine(line);
                    }
                }
            }
        }
    }
}

如果您使用Settings.settings创建和删除设置,则代码可以简化为此,因为Visual Studio会为您的设置对象创建绑定,可以在设计时和运行时进行访问。有关通过Visual Studio IDE使用Settings.settings的信息,请参见以下文章。如果由于某些原因下面的代码不起作用,则可以使用上面的代码:

If you are using Settings.settings to create and delete settings then the code can be simplified to this since Visual Studio will create bindings for your settings object that be accessed at design time and runtime. For information on using Settings.settings through the Visual Studio IDE please see this article. If for some reason the code below doesn't work you can use the code above:

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Diagnostics;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string sFileName = Properties.Settings.Default.ab123;

            // Check if ab123 has a value and the file exists
            if (!string.IsNullOrEmpty(sFileName) && System.IO.File.Exists(sFileName))
            {
                using (StreamReader sr = new StreamReader(sFileName))
                {
                    string line;
                    // Read and display lines from the file until the end of  
                    // the file is reached. 
                    while ((line = sr.ReadLine()) != null)
                    {
                        System.Diagnostics.Debug.WriteLine(line);
                    }
                }
            }
        }
    }
}

这篇关于从C#应用程序中的配置文件中检索值不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆