문자열 또는 메모리 스트림에서 app.config를로드 할 수 있습니까?
-
03-07-2019 - |
문제
다음 코드 줄을 사용하여 다른 위치에서 app.config 파일을로드 할 수 있다는 것을 알고 있습니다.
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", ConfigFile);
여기서 configfile은 전체 경로 위치입니다. 내가하고 싶은 것은 app.config에 암호화 된 파일을로드 할 수 있다는 것입니다. 이상적으로는 파일을로드하여 해독하여 문자열 또는 메모리 스트림에로드하여 app.config 인 것처럼 앱에 전달하려고합니다. 나는 그것의 모든 값을로드하고 수동으로 액세스 할 수 있다는 것을 알고 있지만 .NET의 내장 기능을 사용하여 액세스 할 수 있기를 원합니다. 앱에 파일 이외의 구성 파일을 사용하도록 지시하는 방법이 있습니까?
다른 옵션은 파일을 열고, 해독하고, 임시 파일로 작성 한 다음 위의 코드를 사용하여 그렇게 참조하는 것입니다. 그러나 더 쉬운 방법이 있다면 이상적으로는 찾아보고 싶습니다. 추가 파일을 다루지 않아야합니다.
해결책
지금까지 이것에 대한 답을 얻을 수 없었지만, 나는 일을 생각해 내야했습니다. 이것이 최선의 솔루션은 아니지만 작동합니다. 기본적으로 우리가 한 일은 app.config 파일을 반발하고 새 이름을주었습니다. 앱이 시작되면 반응이 좋은 파일을 사용하여 Decyrpt를 사용하여 Windows Temp 파일에 작성합니다. 이렇게하면 파일이 아무도 찾을 수없는 고유 한 임의 이름임을 보장하며 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 Temp 파일에 작성합니다.
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;
}