开发者

Is there a standard method to create a configuration file for C# program?

In the past I 开发者_如何学Gowould just create a text file with key value pairs for example WIDTH=40 and manually parse the file. This is getting a little cumbersome is there a standard way to do this preferably with inbuilt support from Visual Studio or the .NET framework.


Configuration files are one of the built-in templates. Right-click on your project, choose Add->New Item. In the template box, select configuration file.


You could to create an Application Configuration File in Visual Studio. It's basically and XML file which you can to use to save your application configuration data, but it's not meant to be read as an XML file: .net framework provides some classes to interact with it.

This link can provide some background and sample code: Using Application Configuration Files in .NET

You could to place this code inside your .config file:

<configuration>
    <appSettings>
        <add key="SomeData" value="Hello World!" />
    </appSettings>
</configuration>

And you can read it this way in C# (requires a reference to System.Configuration assembly):

Console.WriteLine(
    "Your config data: {0}",
     ConfigurationManager.AppSettings["SomeData"]);

Note you'll need to escape your data ti fit into a XML file; for instance, a & character would became &amp;


In your C# project look in the folder: Properties and open the file Settings.setting. Here you can specify settings at the user or application level.

The following code sample shows how to use the settings:

public partial class MyControl : UserControl
{
   MyProject.Properties.Settings config_;

   public MyControl 
   {
      InitializeComponent();
      config_ = new MyProject.Properties.Settings();
   }

   public void SaveToConfig()
   {
      // save to configuration file
      config_.ReportFileName = dataFileName.Text;
      config_.Save();
   }

   public void LoadFromConfig()
   {
      string dataFileName = config_.ReportFileName;
   } 
} 

You can also use settings when starting your application, and to modify your settings as you upgrade you application.

static void Main()
   {
   // if user setting program version user setting is less than
   MyProject.Properties.Settings config = new MyProject.Properties.Settings();
   string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
   if (config.Version != version)
   {
      // migrate from version 1.0.2 to future versions here...
      if (config.Version == null)
      {
      }

      config.Upgrade();
      config.Reload();
      config.Version = version;
      config.Save();
   }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜