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)
12921정성태1/14/20225969개발 환경 구성: 624. Docker Desktop에서 별도 서버에 설치한 docker registry에 이미지 올리는 방법
12920정성태1/14/20226735오류 유형: 786. Camtasia - An error occurred with the camera: Failed to Add Video Sampler.
12919정성태1/13/20226576Windows: 199. Host Network Service (HNS)에 의해서 점유되는 포트
12918정성태1/13/20226769Linux: 47. WSL - shell script에서 설정한 환경 변수가 스크립트 실행 후 반영되지 않는 문제
12917정성태1/12/20225936오류 유형: 785. C# - The type or namespace name '...' could not be found (are you missing a using directive or an assembly reference?)
12916정성태1/12/20225706오류 유형: 784. TFS - One or more source control bindings for this solution are not valid and are listed below.
12915정성태1/11/20226026오류 유형: 783. Visual Studio - We didn't find any interpreters
12914정성태1/11/20228047VS.NET IDE: 172. 비주얼 스튜디오 2022의 파이선 개발 환경 지원
12913정성태1/11/20228546.NET Framework: 1133. C# - byte * (바이트 포인터)를 FileStream으로 쓰는 방법 [1]
12912정성태1/11/20229227개발 환경 구성: 623. ffmpeg.exe를 사용해 비디오 파일의 이미지를 PGM(Portable Gray Map) 파일 포맷으로 출력하는 방법 [1]
12911정성태1/11/20226425VS.NET IDE: 171. 비주얼 스튜디오 - 더 이상 만들 수 없는 "ASP.NET Core 3.1 Web Application (.NET Framework)" 프로젝트
12910정성태1/10/20226940제니퍼 .NET: 30. 제니퍼 닷넷 적용 사례 (8) - CPU high와 DB 쿼리 성능에 문제가 함께 있는 사이트
12909정성태1/10/20228302오류 유형: 782. Visual Studio 2022 설치 시 "Couldn't install Microsoft.VisualCpp.Redist.14.Latest"
12908정성태1/10/20226117.NET Framework: 1132. C# - ref/out 매개변수의 IL 코드 처리
12907정성태1/9/20226651오류 유형: 781. (youtube-dl.exe) 실행 시 "This app can't run on your PC" / "Access is denied." 오류 발생
12906정성태1/9/20227305.NET Framework: 1131. C# - 네임스페이스까지 동일한 타입을 2개의 DLL에서 제공하는 경우 충돌을 우회하는 방법 [1]파일 다운로드1
12905정성태1/8/20226960오류 유형: 780. Could not load file or assembly 'Microsoft.VisualStudio.TextTemplating.VSHost.15.0, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
12904정성태1/8/20228950개발 환경 구성: 623. Visual Studio 2022 빌드 환경을 위한 github Actions 설정 [1]
12903정성태1/7/20227543.NET Framework: 1130. C# - ELEMENT_TYPE_INTERNAL 유형의 사용 예
12902정성태1/7/20227584오류 유형: 779. SQL 서버 로그인 에러 - provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.
12901정성태1/5/20227619오류 유형: 778. C# - .NET 5+에서 warning CA1416: This call site is reachable on all platforms. '...' is only supported on: 'windows' 경고 발생
12900정성태1/5/20229302개발 환경 구성: 622. vcpkg로 ffmpeg를 빌드하는 경우 생성될 구성 요소 제어하는 방법
12899정성태1/3/20228786개발 환경 구성: 621. windbg에서 python 스크립트 실행하는 방법 - pykd (2)
12898정성태1/2/20229378.NET Framework: 1129. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 인코딩 예제(encode_video.c) [1]파일 다운로드1
12897정성태1/2/20228202.NET Framework: 1128. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리 [4]파일 다운로드1
12896정성태1/1/202211161.NET Framework: 1127. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성파일 다운로드1
... 16  17  18  19  20  21  22  23  24  25  26  27  28  [29]  30  ...