Matthewj
Matthewj

Reputation: 2022

C# get settings from a file

In c# how can I read the text from a file, then apply a setting from in my program. Config.dat:

autoquit = true

Then if autoquit is true then it'll automatically quit. I know there are built in settings but I would like to know how to convert the settings from within the project to a file & then load the settings when you start the program.

Upvotes: 1

Views: 7021

Answers (3)

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28708

You want to add an <appSettings> section to your configuration file.

If you don't have a config file, right click on your project, click 'Add', click 'New Item....' and selection application (or web) configuration file from the 'General' tab.

Add a setting to your configuration file:

<configuration>
  <appSettings>
    <add key="Autoquit" value="True" />
  </appSettings>
</configuration>

and then in your code, something like

var autoquit = (bool)ConfigurationManager.AppSettings["Autoquit"];

You'll need to add a reference to System.Configuration to access the ConfigurationManager class.

This is the standard, accepted way to store configuration settings. Do not create text files and read string values from them. You can store typed values in the settings section but if you do some research you'll find out how to do that.

Upvotes: 2

crlanglois
crlanglois

Reputation: 3609

The ConfigurationManager class is very helpful for this sort of operation. Refer to this for an example: http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx

You'll find that there are a lot of advantages to using a standard strategy like this.

Upvotes: 2

dahlbyk
dahlbyk

Reputation: 77520

File.ReadAllText() will read text from a file. You could then parse the file with regular expressions, string.Split(), or something else.

You'll get a better answer than this if you show us what you have so far...

Upvotes: 3

Related Questions