如何存储在WinForms应用程序连接字符串?

如何存储在WinForms应用程序连接字符串?

问题描述:

我有一个包含两种形式的应用程序。一种形式中显示的数据从数据库中的字段返回和其它形式打开一个窗口,允许用户选择哪个数据库从获取数据

I have an application that consists of two forms. One form displays data returned from the database in fields and the other form opens a windows that allows the user to select which database to get the data from.

目前,应用不会存储用户的首选数据库。我想存储当前选择的连接字符串是每一个用户选择他们想要的Form2使用数据库的时间。

Currently, the application doesn't store the user's choice of database. I want to store what the currently selected connection string is each time the user selects the database they want to use in form2.

什么是做到这一点的最好方法是什么?如果我做了一个静态类的对象实例来存储这些信息,将是持久化数据为每个表单上使用?

What is the best way to do this? If I made an instance of an object of a static class to store this information, would that persist the data for use on each form?

虽然有内置的.NET capabilites存储用户相关信息(通过注册表,配置文件,设置等),他们似乎是太重了。

Though there are built-in .NET capabilites to store user related information (via Registry, config files, settings etc.) they seem to be too heavy.

我会建议使用纯文本文件并将其保存在用户文件夹:

I would recommend to use plain text file and keep it in user folder:

var userPath = Environment.GetFolderPath(Environment
                                             .SpecialFolder.ApplicationData);
var filename = Path.Combine(userPath, "mysettings");

// Read connection string
var connectionString = File.ReadAllText(filename);

// Write connection string
File.WriteAllText(filename, connectionString);



另外请注意,几乎没有用户将有乐趣的连接字符串的工作。他们宁愿使用单独的表单字段指定数据库名称,服务器,用户名等。要映射这些字段连接字符串,您可以使用 SqlConnectionStringBuilder 类(如果您正在使用MSSQL Server进行操作):

Also note that hardly users will have fun working with connection strings. They would prefer to specify database name, server, username etc. using separate form fields. To map those fields to connection string you may use SqlConnectionStringBuilder class (if you are working with MSSQL Server):

// to connection string
var connectionStringBuilder1 = new SqlConnectionStringBuilder();
connectionStringBuilder1.DataSource = "server";
connectionStringBuilder1.InitialCatalog = "database";
var connectionString = connectionStringBuilder1.ConnectionString;

// from connection string
var connectionStringBuilder2 = new SqlConnectionStringBuilder(connectionString);
var serverName = connectionStringBuilder2.DataSource;
var databaseName = connectionStringBuilder2.InitialCatalog;