雖然目前爲止我還無法得到答案,但我不得不提出解決方法。這可能不是最好的解決方案,但它確實有效。基本上我們所做的就是加入我們的app.config文件,並給它一個新的名字。當應用程序啓動時,它將取得已加密的文件,對其進行解密,並將其寫入Windows臨時文件。這可以確保文件是一些無人可能找到的唯一隨機名稱,我們不必管理這些文件,因爲Windows會自動將它刪除。這樣每次重新啓動,我們都可以重新寫出一個新文件並使用它。以下是有興趣的人的基本代碼片段。
第一種方法LoadFileAppConfig()
將加載文件。在這種情況下,由於它們是服務,我們需要加載執行路徑,並將其傳遞給適當的方法。我們找回解密的app.config的路徑,然後使用SetData()
方法將其設置爲app.config路徑。
/// <summary>
/// Loads the Local App.Config file, and sets it to be the local app.config file
/// </summary>
/// <param name="p_ConfigFilePath">The path of the config file to load, i.e. \Logs\</param>
public void LoadFileAppConfig(string p_ConfigFilePath)
{
try
{
// The app.config path is the passed in path + Application Name + .config
m_LocalAppConfigFile = ProcessLocalAppConfig(p_ConfigFilePath + this.ApplicationName + ".config");
// This sets the service's app.config property
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", m_LocalAppConfigFile);
}
catch (Exception ex)
{
throw ex;
}
}
在這種方法中,我們所得到的文件的路徑,傳遞一個文件關閉以進行解密,並返回一個字符串,然後寫一個文件到我們的Windows臨時文件。
public string ProcessLocalAppConfig(string p_ConfigFilePath)
{
try
{
string fileName = Path.GetTempFileName();
string unencryptedConfig = DecryptConfigData(p_ConfigFilePath);
FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
StreamWriter streamWriter = new StreamWriter(fileStream);
if (!string.IsNullOrEmpty(unencryptedConfig))
{
try
{
streamWriter.BaseStream.Seek(0, SeekOrigin.End);
streamWriter.WriteLine(unencryptedConfig);
}
catch (IOException ex)
{
Debug.Assert(false, ex.ToString());
}
finally
{
streamWriter.Close();
}
return fileName;
}
return null;
}
catch (Exception)
{
throw;
}
}
這最後的方法需要在加密的app.config的路徑,使用我們的解密工具解密文件(確保我們可以將其解密,而且它是正確的文件類型),然後返回解密內容作爲上述方法的字符串。
private string DecryptConfigData(string p_AppConfigFile)
{
string decryptedData = null;
TMS.Pearl.SystemFramework.CryptographyManager.CryptographyManager cryptManager = new TMS.Pearl.SystemFramework.CryptographyManager.CryptographyManager();
try
{
//Attempt to load the file.
if (File.Exists(p_AppConfigFile))
{
//Load the file's contents and decrypt them if they are encrypted.
string rawData = File.ReadAllText(p_AppConfigFile);
if (!string.IsNullOrEmpty(rawData))
{
if (!rawData.Contains("<?xml")) //assuming that all unencrypted config files will start with an xml tag...
{
decryptedData = cryptManager.Decrypt(rawData);
}
else
{
decryptedData = rawData;
}
}
}
}
catch (Exception)
{
throw;
}
return decryptedData;
}
任何具有更多PC知識的人都知道,可以使用filemon來查看任何應用程序的所有IO寫入。 – jgauffin 2011-06-02 11:32:38