Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving Value from Config file in C# Application Doesn't Work

Tags:

c#

config

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>

Declared in the document

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

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"]);

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

How can I fix it?

like image 277
kyoko Avatar asked Sep 04 '14 01:09

kyoko


People also ask

How get values from AppSettings in C#?

To access these values, there is one static class named ConfigurationManager, which has one getter property named AppSettings. We can just pass the key inside the AppSettings and get the desired value from AppSettings section, as shown below.

How does app config work?

App. Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.

How do I access my flask app config?

Flask can be instructed to load all environment variables starting with a specific prefix into the config using from_prefixed_env() . The variables can then be loaded and accessed via the config with a key equal to the environment variable name without the prefix i.e. The prefix is FLASK_ by default.

What is difference between web config and app config?

The web. config file is required for ASP.NET webpages. The app. config file is optional in an application and doesn't have to be used when writing desktop applications.


2 Answers

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>

You can create more settings just like this using a different name

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);
                    }
                }
            }
        }
    }
}

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);
                    }
                }
            }
        }
    }
}
like image 118
Michael Petch Avatar answered Oct 29 '22 16:10

Michael Petch


It looks like you're mixing two models.

  1. Application Settings are defined by declaring a class that derives from ApplicationSettingsBase, though typically you don't do this manually. Instead, let VS create the class for you by going to your project's Properties > Settings tab. This creates a special section in your config file that looks similar to the XML that you posted.
  2. App Settings are defined in a special appSettings configuration section. Only these kinds of settings can be accessed via the ConfigurationManager.AppSettings property, as you're doing. See the XML example below.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ab123" value="D:\ab123\Source\ab123.c" />
  </appSettings>
</configuration>

The reason that you're getting a Win32Exception is because, according to the documentation, it's thrown even if the specified path is null. And ConfigurationManager.AppSettings returns a null reference when the specified setting is not found in the config file. (Just to be clear, it's not found in your case because you're not using the appSettings config section as shown above.)

like image 25
Dave Sexton Avatar answered Oct 29 '22 16:10

Dave Sexton