Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 10개 있습니다.)
VS.NET IDE: 60. Output 경로에 매크로 상수 사용하는 방법
; https://www.sysnet.pe.kr/2/0/688

개발 환경 구성: 91. MSBuild를 이용한 닷넷 응용프로그램의 플랫폼(x86/x64)별 빌드
; https://www.sysnet.pe.kr/2/0/963

개발 환경 구성: 93. MSBuild를 이용한 닷넷 응용프로그램의 다중 어셈블리 출력 빌드
; https://www.sysnet.pe.kr/2/0/965

개발 환경 구성: 102. MSBuild - DefineConstants에 다중 전처리 값 설정
; https://www.sysnet.pe.kr/2/0/988

개발 환경 구성: 115. MSBuild - x86/x64, .NET 2/4, debug/release 빌드에 대한 배치 처리
; https://www.sysnet.pe.kr/2/0/1017

개발 환경 구성: 372. MSBuild - 빌드 전/후, 배포 전/후 실행하고 싶은 Task 정의
; https://www.sysnet.pe.kr/2/0/11507

개발 환경 구성: 452. msbuild - csproj에 환경 변수 조건 사용
; https://www.sysnet.pe.kr/2/0/11985

개발 환경 구성: 580. msbuild의 Exec Task에 robocopy를 사용하는 방법
; https://www.sysnet.pe.kr/2/0/12716

개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법
; https://www.sysnet.pe.kr/2/0/13481

닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
; https://www.sysnet.pe.kr/2/0/13593




msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법

대개의 경우, 닷넷 리소스 파일은 단순히 resx 파일을 포함해 관리할 것입니다. 그런 경우, 프로젝트 파일에는 EmbeddedResource 유형으로 항목이 생기는데요,

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <Compile Update="Resource1.Designer.cs">
      <DesignTime>True</DesignTime>
      <AutoGen>True</AutoGen>
      <DependentUpon>Resource1.resx</DependentUpon>
    </Compile>
  </ItemGroup>

  <ItemGroup>
    <EmbeddedResource Update="Resource1.resx">
      <Generator>ResXFileCodeGenerator</Generator>
      <LastGenOutput>Resource1.Designer.cs</LastGenOutput>
    </EmbeddedResource>
  </ItemGroup>
</Project>

사실 저 설정은 Resource1.resx에 표시된 리소스를 어셈블리 파일 내에 임베딩하는 것과는 무관합니다. 단지, 보는 바와 같이 해당 파일이 편집되면 저장 시 ResXFileCodeGenerator가 동작하게 되고 그 출력으로 Resource1.Designer.cs 파일이 생길 뿐입니다. (resx 파일을 임베딩하지 않도록 설정하는 것은 나중에 언급할 것입니다.)

그나저나, 위의 기본 동작 말고 혹시 리소스를 외부로 분리할 수는 없을까요?




그런 동작을 원한다면, 간단하게는 프로젝트에서 Resource1.resx와 그것이 포함하는 리소스를 전혀 별개의 디렉터리에 복사한 다음 "resgen.exe"를 이용해 resources 파일을 생성하는 방법이 있습니다.

// 아래와 같이 빌드하면 Resource1.resources 파일이 생성됨

c:\temp> resgen Resource1.resx
Read in 1 resources from "Resource1.resx"
Writing resource file...  Done.

그렇다면, 저 과정을 그냥 프로젝트에 포함시켜 놓고 관리를 단일화할 수는 없을까요? 간단하게는 빌드 이벤트에 이렇게 포함시킬 수도 있을 텐데요,

<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
    <Exec Command="resgen &quot;$(ProjectDir)Resource1.resx&quot;" />
</Target>

아쉽게도 실제로 해보면 이런 오류가 발생합니다.

error MSB3073: The command "resgen "c:\temp\ConsoleApp1\ConsoleApp1\Resource1.resx"" exited with code 9009.

왜냐하면, 현재 msbuild에서는 resgen.exe의 위치를 찾지 못하기 때문인데요, 반면 "Developer Command Prompt for VS 2022" 창에서는 Windows SDK가 설치된 경우 다음과 같이 경로 풀이가 됩니다.

c:\temp> which resgen
/c/Program Files (x86)/Microsoft SDKs/Windows/v10.0A/bin/NETFX 4.8 Tools/resgen

그러니까, .NET Framework용 resgen이 활용되고 있던 것입니다. 따라서, 위와 같은 환경에서 실행되기를 원하면 이런 식으로 맞춰줘야 합니다.

<!-- https://learn.microsoft.com/en-us/archive/blogs/lifenglu/how-to-make-generated-resource-class-public -->

<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
    <GetFrameworkSdkPath>
        <Output
            TaskParameter="Path"
            PropertyName="SdkPath" />
    </GetFrameworkSdkPath>
        
    <Exec Command="&quot;$(SdkPath)bin\NETFX 4.8 Tools\resgen&quot; &quot;$(ProjectDir)Resource1.resx&quot;" />
</Target>

또는,
<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
    <Exec Command="&quot;$(TargetFrameworkSDKToolsDirectory)resgen&quot; &quot;$(ProjectDir)Resource1.resx&quot;" />
</Target>

이와 마찬가지로 GenerateResource task를 이용하는 경우에도,

<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
    <GenerateResource Sources="Resource1.resx" OutputResources="Resource1.resources" />
</Target>

이런 오류가 발생할 것입니다. (메시지에 나오는 환경이 갖춰졌다면 오류가 발생하지 않습니다.)

error MSB3091: Task failed because "resgen.exe" was not found, or the correct Microsoft Windows SDK is not installed. The task is looking for "resgen.exe" in the "bin" subdirectory beneath the location specified in the InstallationFolder value of the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.0A\WinSDK-NetFx35Tools-x86. You may be able to solve the problem by doing one of the following: 1) Install the Microsoft Windows SDK. 2) Install Visual Studio 2010. 3) Manually set the above registry key to the correct location. 4) Pass the correct location into the "ToolPath" parameter of the task.


저대로 해주면 되겠지만, 메시지에서 볼 수 있듯이 Visual Studio 2010 시절에나 사용했을 Task라는 의미이므로 이제는 Legacy가 되어 버렸습니다.

어쩔 수 없군요, 만약 resx 파일이 자주 변경되지 않는다면 수작업으로 resgen을 실행해 직접 생성하거나, 아니면 적절한 하드 코딩 또는, 레지스트리에 적절한 경로를 입력해 GenerateResource task가 동작하도록 맞춰주는 것이 좋겠습니다.




한 가지 주의해야 할 부분이 있다면, resx 파일의 경우는 .NET Core/5+ 프로젝트 디렉터리에 함께 있다는 것만으로도 자동으로 출력 어셈블리에 임베딩됩니다. 실제로 다음과 같이 구성한 프로젝트에서,

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
    </PropertyGroup>

</Project>

Resource1.resx 파일이 디렉터리에 있다면 빌드 시 DLL/EXE에 임베딩되는 것을 (용량이 늘어나는 것으로) 확인할 수 있습니다. 만약 이것을 배제하고 싶다면 다음과 같은 식으로 EmbeddedResource 노드를 명시해야 합니다.

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
    </PropertyGroup>

    <ItemGroup>
        <EmbeddedResource Remove="Resource1.resx">
        </EmbeddedResource>
    </ItemGroup>

</Project>

대신, 이런 경우 프로젝트 관리에서도 Resource1.resx 파일이 삭제되므로, 즉 솔루션 탐색기에서 없어지므로 이를 위해 None 노드를 하나 추가하면 됩니다.

<ItemGroup>
    <EmbeddedResource Remove="Resource1.resx">
    </EmbeddedResource>

    <None Include="Resource1.resx">
    </None>

</ItemGroup>

마찬가지로, resgen으로 직접 실행해 Resource1.resources 파일을 생성했다면 프로젝트의 관리를 위해 다음과 같이 추가해 주시면 됩니다.

<ItemGroup>
    <EmbeddedResource Remove="Resource1.resx">
    </EmbeddedResource>

    <None Include="Resource1.resx">
    </None>

    <None Include="Resource1.resources">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
</ItemGroup>

(첨부 파일은 이 글의 예제 파일을 포함합니다.)




그나저나, 언제 한번 기회가 되면 위와 같은 역할만 하는 ResGen 확장을 하나 만들어야겠군요. ^^ 방법은, 이미 아래에 모두 나와 있으니 어렵지는 않습니다.

Resources in .resources files
; https://learn.microsoft.com/en-us/dotnet/core/extensions/create-resource-files#resources-in-resources-files

Tutorial: Create a custom task for code generation
; https://learn.microsoft.com/en-us/visualstudio/msbuild/tutorial-custom-task-code-generation

그냥 좀 귀찮을 뿐!




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/14/2023]

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)
13589정성태3/29/20241207닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241602닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241406오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241695Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241561Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241485개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241516Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241645Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241793개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241323닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241524오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241701닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241970닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241607닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241718닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241641닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241586닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241683닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241784닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241754닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241694닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241809닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241813오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241831오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241691닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241936Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...