引用时将app.config从类库导入到项目中

时间:2012-03-29 20:44:19

标签: c#

我有一个在app.config中有设置的类库。

我知道任何使用此库的项目都需要在其自己的app.config中进行设置。

有没有办法将库中的设置作为模板/默认配置设置?

我想给项目一个起点,但也允许他们覆盖特定配置以满足他们的需求。

我很感激帮助!

3 个答案:

答案 0 :(得分:2)

我过去也需要这样做;我记得当时我做的研究无法将文件标记为“必需”并与参考一起复制。其他论坛和MSDN的建议是手动合并最终位置的App.config文件。

我最终在启动/默认项目中使用XCOPY App.Config文件作为构建后脚本的解决方案进入正确的目标目录。这对我的情况很有效,因为我已经有一个后构建脚本来执行其他任务。

如果确实有更好/更清洁的解决方案,我很乐意听到它。

编辑:以下是我的构建后脚本的简化版本。希望能帮助到你。

@ECHO OFF
SETLOCAL

:: VISUAL STUDIO USAGE
:: $(ProjectDir)..\PostBuild.bat $(TargetName) $(TargetDir) $(ProjectDir) $(ConfigurationName)

SET TargetName=%1
SET TargetDir=%2
SET ProjectDir=%3
SET Configuration=%4

:: XCOPY Usage
:: /I If destination does not exist and copying more than one file, assumes that destination must be a directory.
:: /F Displays full source and destination file names while copying.
:: /Y Suppresses prompting to confirm you want to overwrite an existing destination file.
:: /D Copy only those files whose source time is newer than the destination time.
:: /R Overwrites read-only files.
:: /S Copies directories and subdirectories except empty ones.
:: /E Include empty directories

:: MOVE Usage
:: /Y Suppresses prompting to confirm you want to overwrite an existing destination file.

:: Copy the *.config to output
ECHO F | XCOPY /F /Y /R PathToReferenceLibary\App.config %TargetDir%ReferenceLibary.dll.config

:CLEAN
ECHO =============================================================
ECHO == Clean Unwanted Files
ECHO =============================================================
:: Delete unnecessary default App.config
DEL /Q %TargetDir%App.config

:: Delete license files as they should *never* be shipped!
DEL /Q %TargetDir%*.lic

:EXIT
EXIT ERRORLEVEL

答案 1 :(得分:0)

你不能只是制作一个默认的app.config然后用户可以改变它吗?这将使用户更容易知道可以更改的内容以及这些更改的格式需要看起来像。

答案 2 :(得分:0)

我过去使用的解决方案是在我的库中创建一个名为Configuration的密封类,它也有一个方法IsValid。程序员需要的ClassThatNeedsConfiguration类有一个构造函数,需要传入Configuration类。因此程序员会创建一个Configuration类(带有一些默认值),根据需要进行更改(从app.config,数据库或其他任何东西,我并不关心配置来自何处)并将其传递给构造函数(实际上它是一个工厂方法)以获得有效的ClassThatneedsConfiguration类。 / p>