可以从字符串或内存流加载 App.Config 吗?

发布于 2024-07-10 20:53:31 字数 426 浏览 5 评论 0原文

我知道我可以使用以下代码行从不同位置加载 app.config 文件:

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", ConfigFile);

其中 ConfigFile 是完整路径位置。 我想做的是能够加载已为 app.config 加密的文件。 理想情况下,我希望能够加载文件,解密它,将其加载到字符串或内存流中,然后将其传递给应用程序,就像它是 app.config 一样。 我知道我可以从中加载所有值并手动访问它们,但我希望能够使用 .NET 的内置功能来访问它们。 有没有办法告诉应用程序使用文件以外的配置文件?

另一种选择是打开文件,解密它,将其写入临时文件,然后使用上面的代码以这种方式引用它,但如果有更简单的方法,理想情况下,我想找到它,必须避免处理额外的文件。

I know that I can load an app.config file from a different location using the following line of code:

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", ConfigFile);

where ConfigFile is a full path location. What I'd like to do though is be able to load a file that has been encrypted for the app.config. Ideally, I'd like to be able to load the file, decrypt it, and load it into a string or memory stream and pass it to the app as if it were the app.config. I know I could just load all of the values from it and access them manually, but I'd like to be able to access them using the built in functionality of .NET. Is there a way to tell the app to use the config file from something other than a file?

The other option is to open the file, decrypt it, write it out to a temp file, and then use the above code to reference it that way, but if there was an easier way, ideally, I'd like to find it, to have to avoid dealing with additional files.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

皓月长歌 2024-07-17 20:53:31

虽然到目前为止我还没有得到这个问题的答案,但我必须想出一个解决方法。 这可能不是最好的解决方案,但它确实有效。 基本上我们所做的就是加密我们的 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;
}

While I was never able to get an answer for this so far, I had to come up with a work-around. This may not be the best solution, but it does work. Basically what we've done is encypted our app.config file, and given it a new name. When the app starts up, it will take the encypted file, decyrpt it, and write it to a Windows temp file. This ensures that the file is some unique random name that no one is likely to find, and we don't have to manage the files, as Windows will delete it for us automatically. This way each re-launch we are able to re-write out a new file and use it. Here's the basic code snippets for anyone who is interested.

This first method, LoadFileAppConfig(), will load up the file. In this case, since they are services, we need to load the executing path, and pass it to the appropriate method. We get back the path of the decrypted app.config, and then use the SetData() method to set it to be the app.config path.

/// <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;
    }
}

In this method we are getting the path of the file, passing that file off to be decrypted and returned as a string, and then writing that file to our Windows temp file.

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;
    }
}

This final method takes in the path of the encrypted app.config, uses our Decryption tool to decrypt the file (ensuring that we can decrypt it, and that it is the right file type) and then returning the decrypted contents as a string to the method above.

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文