Best-Practices : how should I store settings in C# (Format/Type)?

坚强是说给别人听的谎言 提交于 2019-12-03 06:04:57

If you want to store application configuration settings, you can leverage the 'AppSettings' in the App.Config or Web.Config file depending on if its a windows or web application. I believe the syntax for reading the configuration values is

string configValue = Configuration.AppSettings["ConfigValueName"];

The configuration file will look like this

<configuration> 
  <appSettings>
    <add key="ConfigValueName" value="ABC"/>
  </appSettings>
</configuration>

With probably lots of other stuff.

If you need to store information about users or other repeated entities in your system, you will need to build a database and write code to persist / read data to / from the database.

You could make a class serializable and automatically serialize it to XML or Binary, OR you could use a SQL database. There are many .net technologies for accesing databases just look up ADO.net , LINQ and the Entity Framework.

The .NET Framework provides some mechanisms for storing and loading application and/or user settings. See "MSDN: Using Settings in C#" for the basics.

To encrypt some sensible data within your configuration files you can also use some standard functions of the .NET Framework. For a short introduction take a look at "Encrypting Configuration Information Using Protected Configuration" and "Encrypting Passwords in a .NET app.config File".

Well the most common way of storing and loading settings is to use some kind of XML data, and making a [Serializable] class and outputting the serialized class to an XML file would work, but you have to keep the following things in mind:

  1. You won't have any control over the input data -- because the XML file can be edited outside of your application, it's possible to have completely nonsensical data loaded
  2. You'll want to have sane defaults for when nodes are missing from the XML. This can be caused by manual edits, or loading an old version of your class into a newer version.
  3. I would personally be very hesitant to store any passwords in a configuration file anywhere, without using some kind of asymmetrical encryption algorithm. If I found a program that was storing my passwords in plain-text in an XML file, I would stop using that program.
Lonzo

You can use the resource files for less sensitive info. For usernames/passwords you need to use an ecrypted text file, or make use of CSPs.

I recommend store where you need to App.Config, an Ini file... Then use the library Config.Net: A comprehensive easy to use and powerful .NET configuration library, fully covered with unit tests and tested in the wild on thousands of servers and applications. Found it in GitHub: https://github.com/aloneguid/config

So you can have your settings in a place, and later, if you need to, move to another.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!