开发者

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 fro开发者_开发知识库m within the project to a file & then load the settings when you start the program.


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...


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜