System.Configuration.ConfigurationSettings.AppSettings question

  • Thread starter Thread starter Dave Hall
  • Start date Start date
D

Dave Hall

I'm having trouble figuring out how to use the
System.Configuration.ConfigurationSettings.AppSettings class. I have an xml
formatted file named MyApp.config. It's in the same directory as MyApp.exe.
The xml looks like this:

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

<configuration>

<appSettings>

<add key="LookFor" value="Found It" />

</appSettings>

</configuration>

MyApp.exe is a generic VB Windows application. In the FormLoad event, I add
the following line and set a breakpoint on it in Visual Studio:

Dim FindThis As String =
System.Configuration.ConfigurationSettings.AppSettings("LookFor")

After stepping past the line, the variable FindThis is still nothing. I
expect it to have a value of "Found It"

What am I missing?

Thanks,

Dave
 
The application config needs a specific name - You're close with what you
have, but just a bit off :
Try "MyApp.exe.config." (no quotes) instead of "MyApp.config"

Other than that, you're pretty dead-on with how to use AppSettings.
 
Thanks Philip. Right after I posted my original question, I realized that I
had put the wrong name in the posting. I am in fact using MyApp.exe.config
as the file name, but it's stull not working. (I've corrected it below) Any
ideas how to troubleshoot it?
 
I discovered that Visual Studio doesn't expect you to name the config file
yourself. When you add the config file to the project, keep the default name
which is App.Config. When Visual studio runs the exe, it copies app.config
to the proper directory for you. For some reason, if I put the file there
myself with the proper name, rather than including it in the project and
letting Visual Studio do it, the value was never read. I'm not sure why I
can't put the file in place myself, but I'm OK with ths solution for now as
long as I understand it. The following article was very helpful:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnadvnet/html/vbnet04222003.asp

Dave
 
Dave - If you're using visual studio, then yes - you need to name it
app.config. What happens when you recompile is that VS.NET clears out your
bin directory, then copies output files to it. app.config's output is
"<targetexe>.config", and so this is placed in your bin. If you are NOT in
vs.net, then you'd simply name it myapp.exe.config, and make sure that at
runtime it's in the same directory as the executable. (This is why naming
it myapp.exe.config in your project doesn't work -- it's not copied to your
output directory, which is where the executable is run from.)
 
Back
Top