class 库的 c# 配置

c# configuration for class library

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

有什么方法可以让我的 class 图书馆读取 app.config?它必须是 app.config,因为我打算在部署期间使用 aspnet_regiis 对其进行加密(我将其重命名为 web.config,对其进行加密并重命名回 app.config)。

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

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

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

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

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

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

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

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

调用应用解密如下:

FileStream fStream = new FileStream("C:\Program Files (x86)\theAPPSettings\ProtectedSettings.dat", FileMode.Open);

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

// Read from the stream and decrypt the data.
byte[] decryptData = Protection.DecryptDataFromStream(entropy, DataProtectionScope.CurrentUser, fStream, Length_of_Stream);

fStream.Close();

string temp = UnicodeEncoding.ASCII.GetString(decryptData);