Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

(시리즈 글이 4개 있습니다.)
.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
; https://www.sysnet.pe.kr/2/0/13336

VS.NET IDE: 197. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C++ 프로젝트의 출력 경로 변경하기
; https://www.sysnet.pe.kr/2/0/13903

VS.NET IDE: 198. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C# 프로젝트의 출력 경로 변경하기
; https://www.sysnet.pe.kr/2/0/13907

VS.NET IDE: 199. Directory.Build.props에 정의한 속성에 대해 Condition 제약으로 값을 변경하는 방법
; https://www.sysnet.pe.kr/2/0/13917




Directory.Build.props에 정의한 속성에 대해 Condition 제약으로 값을 변경하는 방법

지난 글을 통해,

(OneDrive, Dropbox 등의 공유 디렉터리에 있는) C# 프로젝트의 출력 경로 변경하기
; https://www.sysnet.pe.kr/2/0/13907

빌드 결과물을 프로젝트 경로의 하위가 아닌, 별도로 지정한 임시 디렉터리로 지정할 수 있었는데요, 아쉽게도 여기엔 문제가 좀 있습니다. ^^;

한 가지 사례로, Web Application 유형의 프로젝트라면 Visual Studio에서 F5 디버깅 시 기본적으로 ./[프로젝트]/bin 디렉터리를 사용하기 때문에 (별도 디렉터리에 생성된) dll 파일을 찾을 수 없어 오류가 발생합니다.

이 문제를 해결할 수 있는 한 가지 방법으로, Condition 속성을 고려할 수 있는데요,

MSBuild conditions
; https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-conditions?view=vs-2022

그렇다면 이제 필요한 것은 Condition 식 내에 Web Application 프로젝트를 구분할 수 있는 적절한 속성을 찾아야 합니다. 음... 어떤 것이 좋을까요? ^^; 이를 위해 Web Application 프로젝트용의 csproj를 살펴보면,

  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{9F65F804-0A96-4FC4-9F32-6A8DC1A897D7}</ProjectGuid>
    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>WebApplication1</RootNamespace>
    <AssemblyName>WebApplication1</AssemblyName>
    <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
    <MvcBuildViews>false</MvcBuildViews>
    <UseIISExpress>true</UseIISExpress>
    <Use64BitIISExpress />
    <IISExpressSSLPort />
    <IISExpressAnonymousAuthentication />
    <IISExpressWindowsAuthentication />
    <IISExpressUseClassicPipelineMode />
    <UseGlobalApplicationHostFile />
    <NuGetPackageImportStamp>
    </NuGetPackageImportStamp>
  </PropertyGroup>

ProjectTypeGuids, UseIISExpress 정도가 후보로 떠오릅니다. (아무거나 고른) ProjectTypeGuids의 경우 "349c5851-65df-11da-9384-00065b846f21" 값이 있다면 MVC 프로젝트 유형을 나타내므로 Directory.Build.props에 아래와 같이 올바른 문법으로 사용해 볼 수 있지만,

<Project>
    <PropertyGroup Condition="$(ProjectTypeGuids.IndexOf('349c5851-65df-11da-9384-00065b846f21')) == -1">
        <OutputPath>$(BaseOutputPath)\$(Platform)\$(Configuration)\</OutputPath>
        <BaseIntermediateOutputPath>$(BaseOutputPath)\temp</BaseIntermediateOutputPath>
        <IntermediateOutputPath>$(BaseIntermediateOutputPath)\$(Platform)\$(Configuration)\</IntermediateOutputPath>
        ...[생략]...
    </PropertyGroup>
</Project>

실제로 저렇게 해보면 의도한 대로 동작하지 않습니다. 그 이유는, Directory.Build.props의 평가가 너무 이른 시기에 완료되므로 ProjectTypeGuids의 값이 저 시점에는 비어 있기 때문입니다. (UseIISExpress를 사용해도 마찬가지입니다.)

아이러니하게도, Directory.Build.props 파일의 속성이 프로젝트에 대해 매우 이른 시기에 적용된다는 점은 장점이면서도 단점이 된 것입니다. 즉, OutputPath 등의 적용이 프로젝트 로딩 초기에 이뤄지므로 /bin, 또는 /obj 디렉터리가 생성되지 않을 수 있었던 건데요, 오히려 그런 이른 평가 시점으로 인해 Condition 조건에 여타 다른 속성을 사용할 수 없다는 제약으로 작용합니다.

아쉬운 대로, 이런 제약을 해결할 수 있는 방법이 Target을 경유해 속성 변경을 하는 것입니다. 가령, PrepareForBuild 이전에 실행하도록 Target을 정의하고, 그 안에서 CallTarget + Condition을 적용하는 식으로 우회할 수 있습니다.

<Target Name="RollbackProperties">
    <PropertyGroup>
        <BaseOutputPath>$(ProjectDir)bin\</BaseOutputPath>
        <OutputPath>$(ProjectDir)bin\</OutputPath>
        <BaseIntermediateOutputPath>$(ProjectDir)obj\$(Configuration)\</BaseIntermediateOutputPath>
        <IntermediateOutputPath>$(ProjectDir)obj\$(Configuration)\</IntermediateOutputPath>
    </PropertyGroup>
</Target>

<Target Name="CSharpUseTempDirectory" BeforeTargets="PrepareForBuild">
    <CallTarget Condition="'$(UseIISExpress)' == 'true'" Targets="RollbackProperties" />
</Target>

(물론, 시점의 변화로 인해 위와 같은 상황에서 의도했던 /obj, /bin 디렉터리 생성을 막을 수는 없습니다.)




참고로, Condition 등의 조건식에 문자열을 중복 사용할 때는 escape 처리를 해야 합니다. 가령, 다음과 같이 사용하게 되면,

Condition="'$(ProjectTypeGuids.IndexOf('349c5851-65df-11da-9384-00065b846f21'))' == '-1'"

2중으로 홑따옴표를 사용해 오류가 발생합니다.

error  : An unexpected token "..." was found at character position ... in condition 

이런 경우 내부에 중첩된 홑따옴표를 backtick(`)으로 escape 처리하면 됩니다.

Condition="'$(ProjectTypeGuids.IndexOf(`349c5851-65df-11da-9384-00065b846f21`))' == '-1'"




만약 특정 속성의 값이 궁금하다면 Message Task를 사용해 확인해 볼 수 있습니다. 가령 다음과 같이 속성을 정의했다면,

<Project>

    ...[생략]...

    <PropertyGroup>
        <TestProp>$(ProjectTypeGuids)</TestProp>
    </PropertyGroup>
</Project>

적절하게 Target을 정의한 후, Message Task를 추가하면 빌드 시에 Output 창을 통해 속성 값을 확인할 수 있습니다.

<Project>
    ...[생략]...

    <Target Name="mywork" AfterTargets="CoreBuild">
        <Message Importance="high" Text="[TEST] $(TestProp)"/>
    </Target>
</Project>




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 5/1/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11836정성태3/5/201923376오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201921847.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201920642개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201921200개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201917112오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201916943오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201916631오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201918324개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201926226개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201919159오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201919347오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201924614개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201919051오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201920651오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201919002오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201919752오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201922823오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201922081Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201920176VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201916525오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201919993Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201918217오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201917072오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201918369.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201915699오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201920944오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...