0

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

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

4

2 回答 2

2

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

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

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

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

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

于 2018-06-13T10:38:28.113 回答
0

最后(根据@Stand__Sure 和@tigerswithguitars,我在我的解决方案中创建了一个新项目,它将是一个控制台应用程序。它将在部署时执行。感谢 Stand__Sure 提供到https://docs.microsoft.com/的链接zh-CN/dotnet/标准/安全/如何使用数据保护

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

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);
于 2018-06-14T13:54:54.847 回答