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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  [22]  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13097정성태7/12/20225803오류 유형: 817. Golang - binary.Read: invalid type int32
13096정성태7/8/20228697.NET Framework: 2030. C# 11 - UTF-8 문자열 리터럴
13095정성태7/7/20226739Windows: 208. AD 도메인에 참여하지 않은 컴퓨터에서 Kerberos 인증을 사용하는 방법
13094정성태7/6/20226500오류 유형: 816. Golang - "short write" 오류 원인
13093정성태7/5/20227370.NET Framework: 2029. C# - HttpWebRequest로 localhost 접속 시 2초 이상 지연
13092정성태7/3/20228343.NET Framework: 2028. C# - HttpWebRequest의 POST 동작 방식파일 다운로드1
13091정성태7/3/20227274.NET Framework: 2027. C# - IPv4, IPv6를 모두 지원하는 서버 소켓 생성 방법
13090정성태6/29/20226325오류 유형: 815. PyPI에 업로드한 패키지가 반영이 안 되는 경우
13089정성태6/28/20226801개발 환경 구성: 646. HOSTS 파일 변경 시 Edge 브라우저에 반영하는 방법
13088정성태6/27/20225773개발 환경 구성: 645. "Developer Command Prompt for VS 2022" 명령행 환경의 폰트를 바꾸는 방법
13087정성태6/23/20228818스크립트: 41. 파이썬 - FastAPI / uvicorn 호스팅 환경에서 asyncio 사용하는 방법 [1]
13086정성태6/22/20228265.NET Framework: 2026. C# 11 - 문자열 보간 개선 2가지파일 다운로드1
13085정성태6/22/20228359.NET Framework: 2025. C# 11 - 원시 문자열 리터럴(raw string literals)파일 다운로드1
13084정성태6/21/20226791개발 환경 구성: 644. Windows - 파이썬 2.7을 msi 설치 없이 구성하는 방법
13083정성태6/20/20227434.NET Framework: 2024. .NET 7에 도입된 GC의 메모리 해제에 대한 segment와 region의 차이점 [2]
13082정성태6/19/20226494.NET Framework: 2023. C# - Process의 I/O 사용량을 보여주는 GetProcessIoCounters Win32 API파일 다운로드1
13081정성태6/17/20226518.NET Framework: 2022. C# - .NET 7 Preview 5 신규 기능 - System.IO.Stream ReadExactly / ReadAtLeast파일 다운로드1
13080정성태6/17/20227183개발 환경 구성: 643. Visual Studio 2022 17.2 버전에서 C# 11 또는 .NET 7.0 preview 적용
13079정성태6/17/20224798오류 유형: 814. 파이썬 - Error: The file/path provided (...) does not appear to exist
13078정성태6/16/20226990.NET Framework: 2021. WPF - UI Thread와 Render Thread파일 다운로드1
13077정성태6/15/20227205스크립트: 40. 파이썬 - PostgreSQL 환경 구성
13075정성태6/15/20226167Linux: 50. Linux - apt와 apt-get의 차이 [2]
13074정성태6/13/20226484.NET Framework: 2020. C# - NTFS 파일에 사용자 정의 속성값 추가하는 방법파일 다운로드1
13073정성태6/12/20226772Windows: 207. Windows Server 2022에 도입된 WSL 2
13072정성태6/10/20227045Linux: 49. Linux - ls 명령어로 출력되는 디렉터리 색상 변경 방법
13071정성태6/9/20227644스크립트: 39. Python에서 cx_Oracle 환경 구성
... 16  17  18  19  20  21  [22]  23  24  25  26  27  28  29  30  ...