c#配置类库

时间:2018-06-13 10:35:32

标签: c# app-config class-library aspnet-regiis.exe

我有一个类库,默认情况下没有app.config。该库的调用应用程序是" explorer.exe"我无法使用explorer.exe.config添加我的设置。

有什么方法可以让我的类库读取app.config吗?它需要是一个app.config,因为我打算在部署期间使用aspnet_regiis加密它(我将它重命名为web.config,加密它并将其重命名为app.config)。

2 个答案:

答案 0 :(得分:2)

在C#中,唯一重要的配置是输出项目的app.config。对于控制台应用程序,这将是.exe配置。哪个会在bin中显示为{your app name}.exe.config

您可以使用ConfigurationManager DLL中的System.Configuration来阅读此文件。所有这些用法都将指向执行代码的配置文件,即使在类库中也是如此。因此,需要将导入的类库中所需的任何其他配置添加到此文件中。这是处理配置的规范方式。

如果您真的想要其他配置文件,可以使用:

ConfigurationManager.OpenMappedExeConfiguration(
            new ExeConfigurationFileMap
            {
                ExeConfigFilename = overrideConfigFileName
            }, 
            ConfigurationUserLevel.None)

overrideConfigFileName指向其他app.config文件的位置。您可以将类库中的文件设置为Content,并确保在构建时将其复制到输出目录中。然后,您必须确保它包含在最终部署包中,并且所有路径都匹配。

答案 1 :(得分:0)

最后(根据@Stand__Sure和@tigerswithguitars,我在我的解决方案中创建了一个新项目,它将是一个控制台应用程序。它将在部署时执行。 感谢Stand__Sure链接到https://docs.microsoft.com/en-us/dotnet/standard/security/how-to-use-data-protection

控制台应用程序执行以下操作:

id

调用应用程序按如下方式对其进行解密:

private static void Run()
{
    try
    {
        // Get unencrypted data from Settings.dat
        string[] unencrypted = File.ReadAllLines("C:\\Program Files (x86)\\theAPPSettings\\Settings.dat");

        string unencryptedGuid = unencrypted[0]; //its only 1 setting that I'm interested in

        // Create a file.
        FileStream fStream = new FileStream("C:\\Program Files (x86)\\theAPPSettings\\ProtectedSettings.dat", FileMode.OpenOrCreate);

        byte[] toEncrypt = UnicodeEncoding.ASCII.GetBytes(unencryptedGuid);                

        byte[] entropy = UnicodeEncoding.ASCII.GetBytes("A Shared Phrase between the encryption and decryption");

        // Encrypt a copy of the data to the stream.
        int bytesWritten = Protection.EncryptDataToStream(toEncrypt, entropy, DataProtectionScope.CurrentUser, fStream);

        fStream.Close();

        File.Delete("C:\\Program Files (x86)\\theAPPSettings\\Settings.dat");

        //Console.ReadKey();
    }
    catch (Exception e)
    {
        Console.WriteLine("ERROR: " + e.Message);
    }
}