views:

51

answers:

2

Hello,

i have a config file like this:

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

configuration

  appSettings

    add key="PortName" value="COM4"

    add key="BaudRate" value="9600"

   add key="DataBits" value="8" 

  appSettings

configuration

... and then i want to access app.config values with this code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO.Ports;

using System.Configuration;


namespace SystemToControler

{

    public class ConnectionProtocol : IConnectionProtocol
    {
        SerialPort serialPort = new SerialPort();

        public ConnectionProtocol()
        {
            serialPort.PortName = ConfigurationManager.AppSettings["PortName"];
            serialPort.BaudRate = Convert.ToInt32(ConfigurationManager.AppSettings["BaudRate"]);
            serialPort.DataBits = Convert.ToInt32(ConfigurationManager.AppSettings["DataBits"]);
        }
    }
}

... and it tells me i that those keys does not exist.

What am i doing wrong??? Please help!

+1  A: 

Wild guess inferred from comments: be sure to put your config in the app.config of the running app. Configuration from other projects are never read.

example: If you have a solution with 2 projects, ClassLibrary1 with an app.config and Winform1 with its own app.setting, and Winform1 depends on ClassLibrary1, building Winform1 will give a directory with those files:

ClassLibrary1.dll

ClassLibrary.dll.config

Winform1.exe

Winform1.exe.config

When Winform1.exe is running, the configuration is read from Winform1.exe.config, all other configuration files are useless.

Cédric Rup
Thank you for the answer.
dani
+1  A: 

Consider getting application configuration from within your winforms project and instantiating your ConnectionProtocol object from there as well. Your current method couples your ConnectionProtocol class to application configuration classes it doesn't need.

For example, in your application, do this:

string portName = ConfigurationManager.AppSettings["PortName"];
int baudRate = Convert.ToInt32(ConfigurationManager.AppSettings["BaudRate"]);
int dataBits = Convert.ToInt32(ConfigurationManager.AppSettings["DataBits"]);

ConnectionProtocol protocol = new ConnectionProtocol(portName, baudRate, dataBits);

related questions