ILSpy의 nuget 라이브러리 버전 - ICSharpCode.Decompiler
이번에도 ^^ 트윗으로 본 내용을 소개합니다.
Did you know that ILSpy is providing a nuget package allowing you to list (in 8 lines of code) the string literals compiled in a .NET assembly?
; https://twitter.com/chnasarre/status/1685350012614578176
ILSpy의 nuget 버전으로 ICSharpCode.Decompiler가 있는데요, 이미 우리에게는
Visual Studio에서도 심심치 않게 봤을 정도로 은근 낯설지 않은 라이브러리입니다. ^^
ICSharpCode.Decompiler
; https://www.nuget.org/packages/ICSharpCode.Decompiler
다음은 닷넷 어셈블리의
"#Strings" 영역을 뒤져 문자열 리터럴을 출력하는 소스 코드로,
using ICSharpCode.Decompiler.Metadata;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
namespace ConsoleApp1;
// Install-Package ICSharpCode.Decompiler
internal class Program
{
static void Main(string[] args)
{
string dllPath = typeof(Program).Assembly.Location;
using (var peFile = new PEFile(dllPath))
{
MetadataReader metadata = peFile.Metadata;
UserStringHandle handle = MetadataTokens.UserStringHandle(0);
do
{
string literal = metadata.GetUserString(handle);
Console.WriteLine($"'{literal}'");
handle = metadata.GetNextHandle(handle);
} while (!handle.IsNil);
}
}
}
얼핏 ^^ ICSharpCode.Decompiler가 제공하는 듯하지만 (덧글에 "
@Lucas Trzesniewski"가 지적한 것처럼) 실제로는 System.Reflection.Metadata로 연결시켜 접근하고 있습니다.
그래서 위의 소스 코드를 ICSharpCode 참조 없이 순수하게 System.Reflection.Metadata만을 이용해 다음과 같이 만들 수 있습니다.
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
namespace ConsoleApp1;
internal class Program
{
static void Main(string[] args)
{
string dllPath = typeof(Program).Assembly.Location;
FileStream stream = File.OpenRead(dllPath);
PEReader peReader = new PEReader(stream);
MetadataReader metadata = peReader.GetMetadataReader();
UserStringHandle handle = MetadataTokens.UserStringHandle(0);
do
{
string literal = metadata.GetUserString(handle);
Console.WriteLine($"'{literal}'");
handle = metadata.GetNextHandle(handle);
} while (!handle.IsNil);
}
}
오호~~~ 저도 PortableExecutable에 대한
PEReader 타입이 있는지 오늘 처음 알았습니다. ^^
그나저나, 제목과는 달리 (ICSharpCode.Decompiler가 아닌) System.Reflection.Metadata에 대한 소개가 되었군요. ^^
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]