Problems while reading value from app.config file

2019-05-21 00:05发布

问题:

I am making one windows application in c# in where i added one file as app.config file.I have written some code in that file as

    <appSettings>
       <add key ="FlagForArchiving" value="true"/>
    </appSettings>

In 'program.cs' file i am reading this value as

ConfigurationSettings.AppSettings["FlagForArchiving"].ToString();

On local machine i can retrieve value from config file but whenever i am building that application and running on any other machine then I cant read the value from config file.I am trying to run my application on windows 7.Please help me.Thanks in advance.

回答1:

app.config is renamed to <MyProgramName>.exe.config when you build. When your program runs it will look for that <MyProgramName>.exe.config file, not app.config.

You need to deploy the renamed file (<MyProgramName>.exe.config) along with your program.

In your case, you need to copy over OBViewer.exe, OBViewer.exe.config, and any other files that OBViewer.exe depends on (e.g. other .dll assemblies in your debug/release directory).

By the way, this renamed file is often commonly referred to as "app.config", even if it doesn't have the same filename.



回答2:

and the app.config file exists on the other machine? Before reading check if it exists

The exception you get says whats incorrect: "FileNotFoundException"

EDIT here is the correct way!

if (File.Exists(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile))
{
    MessageBox.Show(ConfigurationSettings.AppSettings["FlagForArchiving"].ToString());
}