如何将 dll 配置文件添加到将 dll 作为参考添加的项目中?

How to add a dll config file to a project that add the dll as reference?

我写了一个UserLogin dll。 该 dll 使用带有一些默认参数的 App.Config 文件。为了更好的文件系统可读性,我已将配置文件重命名为 UserLogin.Config。

我编写了一个需要用户登录的新应用程序。我添加了 UserLogin.dll 作为对新应用程序的引用。问题是配置文件没有添加参考。我必须手动将它添加到 bin\debug 文件夹才能通过 Visual Studio.

运行 应用程序

我在部署它时没有这样的问题,因为我将配置文件添加为设置的一部分。

将配置文件添加到新应用程序以便我可以在开发环境中运行它的正确方法是什么?

以下是 UserLogin.config 文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="IsTestEnvironment" value="false" />
        <add key="AllowedUserForTestEnvironment" value="ehh" />
        <add key="EnableLogging" value="false" />
     </appSettings>
</configuration>

从UserLogin.config文件中读取的class:

public static class ConfigurationReader
{
    private static AppSettingsSection _appSettings;

    public static AppSettingsSection AppSettings
    {
        get
        {
            if (_appSettings == null)
            {
                var userPreferencesConfigFileMap = new ExeConfigurationFileMap();
                userPreferencesConfigFileMap.ExeConfigFilename = "UserLogin.config";
                var userPreferencesConfig = ConfigurationManager.OpenMappedExeConfiguration(userPreferencesConfigFileMap, ConfigurationUserLevel.None);
                _appSettings = (AppSettingsSection)userPreferencesConfig.GetSection("appSettings");                                        
            }

            return _appSettings;
        }
    }

    public static bool IsTestEnvironment
    {
        get
        {
            return bool.Parse(AppSettings.Settings["IsTestEnvironment"].Value);
        }
    }

    public static string AllowedUserForTestEnvironment
    {
        get
        {
            return AppSettings.Settings["AllowedUserForTestEnvironment"].Value;
        }
    }

    public static string EnableLogging
    {
        get
        {
            return AppSettings.Settings["EnableLogging"].Value;
        }
    }
}

使用UserLogin.dll的新应用程序:

问题是您已将配置文件名重命名为自定义名称。

理想情况下,任何 DLL 都可以使用来自父 Exes App.config 的配置,您只需将应用程序设置添加到使用该 dll 的应用程序 (exe) 的 App.config 文件中。

为什么要这样分开。这不是一个好的做法。

既然你把它分开了,它就像拥有一个自定义的 xml 配置文件一样。

在这种情况下,您可以尝试添加 Post-Build 或 Pre-Build 命令,使用 XCOPY 将配置文件复制到正确的输出目录,以便 DLL 获取它。

右键单击项目属性,转到 Pre-Build 事件,添加如下命令

xcopy /y "$(SolutionDir)MyProject\myFile.xxx" "$(OutputDir)"

请注意,您可能需要更改路径和文件名以满足您的需要。