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

비밀번호

댓글 작성자
 




1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13853정성태12/26/20244766디버깅 기술: 213. Windbg - swapgs 명령어와 (Ring 0 커널 모드의) FS, GS Segment 레지스터
13852정성태12/25/20245861디버깅 기술: 212. Windbg - (Ring 3 사용자 모드의) FS, GS Segment 레지스터파일 다운로드1
13851정성태12/23/20245071디버깅 기술: 211. Windbg - 커널 모드 디버깅 상태에서 사용자 프로그램을 디버깅하는 방법
13850정성태12/23/20246182오류 유형: 940. "Application Information" 서비스를 중지한 경우, "This file does not have an app associated with it for performing this action."
13849정성태12/20/20246179디버깅 기술: 210. Windbg - 논리(가상) 주소를 Segmentation을 거쳐 선형 주소로 변경
13848정성태12/18/20245670디버깅 기술: 209. Windbg로 알아보는 Prototype PTE파일 다운로드2
13847정성태12/18/20245751오류 유형: 939. golang - 빌드 시 "unknown directive: toolchain" 오류 빌드 시 이런 오류가 발생한다면?
13846정성태12/17/20246289디버깅 기술: 208. Windbg로 알아보는 Trans/Soft PTE와 2가지 Page Fault 유형파일 다운로드1
13845정성태12/16/20245132디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE)
13844정성태12/14/20246617디버깅 기술: 206. Windbg로 알아보는 PFN (_MMPFN)파일 다운로드1
13843정성태12/13/20245161오류 유형: 938. Docker container 내에서 빌드 시 error MSB3021: Unable to copy file "..." to "...". Access to the path '...' is denied.
13842정성태12/12/20245329디버깅 기술: 205. Windbg - KPCR, KPRCB
13841정성태12/11/20245909오류 유형: 937. error MSB4044: The "ValidateValidArchitecture" task was not given a value for the required parameter "RemoteTarget"
13840정성태12/11/20245247오류 유형: 936. msbuild - Your project file doesn't list 'win' as a "RuntimeIdentifier"
13839정성태12/11/20246118오류 유형: 936. msbuild - error CS1617: Invalid option '12.0' for /langversion. Use '/langversion:?' to list supported values.
13838정성태12/4/20245905오류 유형: 935. Windbg - Breakpoint 0's offset expression evaluation failed.
13837정성태12/3/20246737디버깅 기술: 204. Windbg - 윈도우 핸들 테이블 (3) - Windows 10 이상인 경우
13836정성태12/3/20245284디버깅 기술: 203. Windbg - x64 가상 주소를 물리 주소로 변환 (페이지 크기가 2MB인 경우)
13835정성태12/2/20246681오류 유형: 934. Azure - rm: cannot remove '...': Directory not empty
13834정성태11/29/20246676Windows: 275. C# - CUI 애플리케이션과 Console 윈도우 (Windows 10 미만의 Classic Console 모드인 경우) [1]파일 다운로드1
13833정성태11/29/20246051개발 환경 구성: 737. Azure Web App에서 Scale-out으로 늘어난 리눅스 인스턴스에 SSH 접속하는 방법
13832정성태11/27/20245670Windows: 274. Windows 7부터 도입한 conhost.exe
13831정성태11/27/20245045Linux: 111. eBPF - BPF_MAP_TYPE_PERF_EVENT_ARRAY, BPF_MAP_TYPE_RINGBUF에 대한 다양한 용어들
13830정성태11/25/20246538개발 환경 구성: 736. 파이썬 웹 앱을 Azure App Service에 배포하기
13829정성태11/25/20246643스크립트: 67. 파이썬 - Windows 버전에서 함께 설치되는 py.exe
13828정성태11/25/20245174개발 환경 구성: 735. Azure - 압축 파일을 이용한 web app 배포 시 디렉터리 구분이 안 되는 문제파일 다운로드1
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...