開發環境用自己的 SQL Server,客戶環境 IP、實例名、資料庫名、帳密全不同。硬編碼連線字串會導致部署即報錯。
<!-- app.config -->
<connectionStrings>
<add name="DefaultConn" connectionString="" />
</connectionStrings>
<appSettings>
<add key="DbServer" value="." />
<add key="DbName" value="MyDB" />
<add key="DbUser" value="sa" />
<add key="DbPwd" value="" />
<add key="UseIntegratedSecurity" value="false" />
</appSettings>
using System.Configuration;
using System.Data.SqlClient;
public string BuildConnectionString() {
var builder = new SqlConnectionStringBuilder {
DataSource = ConfigurationManager.AppSettings["DbServer"],
InitialCatalog = ConfigurationManager.AppSettings["DbName"],
IntegratedSecurity = bool.Parse(ConfigurationManager.AppSettings["UseIntegratedSecurity"])
};
if (!builder.IntegratedSecurity) {
builder.UserID = ConfigurationManager.AppSettings["DbUser"];
builder.Password = ConfigurationManager.AppSettings["DbPwd"]; // 生產環境建議加密存儲
}
return builder.ConnectionString;
}
WinForms/WPF 中做一個簡單的設定對話框,包含:
// 簡單示例:使用 DPAPI (ProtectedData) 加密
byte[] entropy = Encoding.UTF8.GetBytes("MyApp_Salt");
byte[] plain = Encoding.UTF8.GetBytes(password);
byte[] encrypted = ProtectedData.Protect(plain, entropy, DataProtectionScope.CurrentUser);
string cipherText = Convert.ToBase64String(encrypted); // 存入 config
// 解密
byte[] cipher = Convert.FromBase64String(cipherText);
byte[] decrypted = ProtectedData.Unprotect(cipher, entropy, DataProtectionScope.CurrentUser);
password = Encoding.UTF8.GetString(decrypted);
AppName.exe.config