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)
13492정성태12/19/20232483개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232312Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232445개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232218개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232199오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232487개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232300개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232172오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232284개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232406닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20233106닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232414개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232821개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232455개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232704닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232466닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232526닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232338개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232620닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232285C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232418Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232749닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232567닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232409닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232545오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232696닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...