これまでのところ、これに対する答えを得ることができませんでしたが、回避策を考え出す必要がありました。これは最善の解決策ではないかもしれませんが、うまくいきます。基本的に、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;
}