C# 對WinForm應用程序的App.config的使用及加密


原文地址:http://blog.163.com/zhou_zzq/blog/static/1019622120137621739874/
 
我們在寫C#應用程序時,在工程文件中放置一個app.config,程序打包時,系統會將該配置文件自動編譯為與程序集同名的.exe.config 文件。作用就是應用程序安裝后,只需在安裝目錄中找到該文件,需改字符串內容,就可以改變運行參數,而不用修改源程序代碼。例如:可以使用配置文件保存數據庫連接字符串;在應用程序中顯示變動的文字信息等等。
 
         因為對其使用方法的不了解,大多數人選擇了自己重建配置文件並自行管理,實際上這個文件是可以被用戶操作的。App.config文件為Xml文檔格式,可在文件中添加任意數量的字符串,應用程序在運行時可以讀取這些字符串。
 
一、操作攻略
1. 向項目添加app.config文件:
右擊項目名稱,選擇“添加”→“添加新建項”,在出現的“添加新項”對話框中,選擇“添加應用程序配置文件”;如果項目以前沒有配置文件,則默認的文件名稱為“app.config”,單擊“確定”。出現在設計器視圖中的app.config文件為:
<?xmlversion="1.0"encoding="utf-8" ?>
<configuration>
</configuration>
在項目進行編譯后,在bin\Debuge文件下,將出現兩個配置文件(以本項目為例),一個名為“JxcManagement.EXE.config”,另一個名為“JxcManagement.vshost.exe.config”。第一個文件為項目實際使用的配置文件,在程序運行中所做的更改都將被保存於此;第二個文件為原代碼“app.config”的同步文件,在程序運行中不會發生更改。
2. connectionStrings配置節:
請注意:如果您的SQL版本為2005 Express版,則默認安裝時SQL服務器實例名為localhost\SQLExpress,須更改以下實例中“Data Source=localhost;”一句為“Data Source=localhost\SQLExpress;”,在等於號的兩邊不要加上空格。
<!--數據庫連接串-->
<connectionStrings>
<clear />
<addname="conJxcBook"
connectionString="Data Source=localhost;Initial Catalog=jxcbook;User ID=sa;password=********"providerName="System.Data.SqlClient" />
</connectionStrings>
3. appSettings配置節:
appSettings配置節為整個程序的配置,如果是對當前用戶的配置,請使用userSettings配置節,其格式與以下配置書寫要求一樣。
<!--進銷存管理系統初始化需要的參數-->
<appSettings>
<clear />
<addkey="userName"value="" />
<addkey="password"value="" />
<addkey="Department"value="" />
<addkey="returnValue"value="" />
<addkey="pwdPattern"value="" />
<addkey="userPattern"value="" />
</appSettings>
4.讀取與更新app.config
對於app.config文件的讀寫,參照了網絡文章:http://www.codeproject.com/csharp/ SystemConfiguration.asp標題為“Read/Write App.Config File with .NET 2.0”一文。請注意:要使用以下的代碼訪問app.config文件,除添加引用System.Configuration外,還必須在項目添加對System.Configuration.dll的引用。
4.1 讀取connectionStrings配置節
///<summary>
///依據連接串名字connectionName返回數據連接字符串
///</summary>
///<param name="connectionName"></param>
///<returns></returns>
private static string GetConnectionStringsConfig(string connectionName)
{
string connectionString =ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();
Console.WriteLine(connectionString);
return connectionString;
}
4.2 更新connectionStrings配置節
///<summary>
///更新連接字符串
///</summary>
///<param name="newName">連接字符串名稱</param>
///<param name="newConString">連接字符串內容</param>
///<param name="newProviderName">數據提供程序名稱</param>
private static void UpdateConnectionStringsConfig(string newName,string newConString,string newProviderName)
{
bool isModified = false; //記錄該連接串是否已經存在
//如果要更改的連接串已經存在
if (ConfigurationManager.ConnectionStrings[newName] != null)isModified = true;
//新建一個連接字符串實例
ConnectionStringSettings mySettings =new ConnectionStringSettings(newName, newConString, newProviderName);
// 打開可執行的配置文件*.exe.config
Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// 如果連接串已存在,首先刪除它
if (isModified)config.ConnectionStrings.ConnectionStrings.Remove(newName);
// 將新的連接串添加到配置文件中.
config.ConnectionStrings.ConnectionStrings.Add(mySettings);
// 保存對配置文件所作的更改
config.Save(ConfigurationSaveMode.Modified);
// 強制重新載入配置文件的ConnectionStrings配置節
ConfigurationManager.RefreshSection("ConnectionStrings");
}
4.3 讀取appStrings配置節
///<summary>
///返回*.exe.config文件中appSettings配置節的value項
///</summary>
///<param name="strKey"></param>
///<returns></returns>
private static string GetAppConfig(string strKey)
{
  foreach (string key in ConfigurationManager.AppSettings)
    if (key == strKey)return ConfigurationManager.AppSettings[strKey];
return null;
}
4.4 更新appStrings配置節
///<summary>
///在*.exe.config文件中appSettings配置節增加一對鍵、值對
///</summary>
///<param name="newKey"></param>
///<param name="newValue"></param>
private static void UpdateAppConfig(string newKey, string newValue)
{
bool isModified = false;
foreach (string key in ConfigurationManager.AppSettings)
{
if(key==newKey)
{
isModified = true;
}
}
// Open App.Config of executable
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// You need to remove the old settings object before you can replace it
if (isModified)
{
config.AppSettings.Settings.Remove(newKey);
}
// Add an Application Setting.
config.AppSettings.Settings.Add(newKey,newValue);
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
}
 
二、對配置信息數據加密
默認情況下,我們需要對App.config文件里的connectionStrings片斷進行加密處理,ASP.NET IIS 注冊工具 (Aspnet_regiis.exe)可以勝任這個工作,但這個工具只能針對ASP.NET的Web.config文件,難道我們就沒有辦法了嗎?答案當然是否定的。
 
配置選項
-pdf section webApplicationDirectory 對指定物理(非虛擬)目錄中的 Web.config 文件的指定配置節進行解密。
-pef section webApplicationDirectory 對指定物理(非虛擬)目錄中的 Web.config 文件的指定配置節進行加密。
-pdf 和-pef 參數是對指定的物理目錄里的Web.config文件進行加密,我們可以先將App.config文件改名為Web.config,通過這兩個參數便可以“騙”過系統,讓它將指定的配置節進行加密,我們只需要將加密后的文件名改回App.config即可,我們來實驗一下:
 
    第一步:先將目錄下的App.config改名為Web.config。
    第二步:打開SDK命令提示,輸入命令:aspnet_regiis -pef "配置節" "目錄",以我的項目為例,加密前的config文件內容如下:
 
 1<?xml version="1.0" encoding="utf-8"?>
 2<configuration>
 3  <configSections>
 4    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
 5  </configSections>
 6  <dataConfiguration defaultDatabase="Connection String" />
 7  <connectionStrings>
 8    <add name="Connection String" connectionString="Database=LocomotiveStat;Server=10.167.61.49;User ID=sa;Password=sa;"
 9      providerName="System.Data.SqlClient" />
10  </connectionStrings>
11</configuration>
 
輸入命令:aspnet_regiis -pef "connectionStrings" "E:\開發目錄",加密后的config文件內容如下:
 
 1<?xml version="1.0" encoding="utf-8"?>
 2<configuration>
 3  <configSections>
 4    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
 5  </configSections>
 6  <dataConfiguration defaultDatabase="Connection String" />
 7  <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
 8    <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
 9      xmlns="http://www.w3.org/2001/04/xmlenc#">
10      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
11      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
12        <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
13          <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
14          <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
15            <KeyName>Rsa Key</KeyName>
16          </KeyInfo>
17          <CipherData>
18            
<CipherValue>g2QFQqbHU1L6WUPYqjADqFAvHcdq/7dqCd1U9GlQFEi/nHDVHjqsWvjNywOZtQQg7Q/yW7g8xlRCo0h2+yYd/tQTNoVMu/RKdJmSjZMnmnwpWq+S2VEWK4U106JQwLCfBR/bAF4DHvG47B9KB0JbRfXBt5V2wJVaAI9u3kzuj50=</CipherValue>
19          </CipherData>
20        </EncryptedKey>
21      </KeyInfo>
22      <CipherData>
23        
<CipherValue>blwV/ZW1izFZL80YL5RkcjrIjWkQ0L1gJhgZbxEzzTgOcT24ihrAnv3/rDCG+WIZ7TL5D/rMm7dQwkIsij1Sh3befg6F3+pxcW4oe1w/bovIKuzjs3tokUpBvTTj+fsCs2W/MWUhQaWMKQWkHfS2Ajt6gL6MTYtb3pfQUp0pdHbeRxoqdiAksQ1Zzsi1FtRTi7gTT7hnpF0pJs+W9mxTVDMO/qSZXfXLOEMIs/A5ExcfvR5GjpaPuDeLuSsCN3XtjaiXzaDQ3It7j+r66+L2C0xvEhbT9SsG</CipherValue>
24      </CipherData>
25    </EncryptedData>
26  </connectionStrings>
27</configuration>
 
    由此可見,我們已經完成了任務,現在只需要將Web.config文件名改回App.config即可,在應用程序項目中無需對該文件進行解密操作,.NET框架會自動替我們完成,如果想解密該文件也很簡單,在SDK命令提示里輸入aspnet_regiis -pdf "配置節" "目錄"即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM