Namespace: System.Reflection.Metadata
Namespace: System.Reflection.Metadata
Assembly: System.Reflection.Metadata.dll
This namespace provides types for accessing and manipulating metadata of .NET assemblies. It's a low-level API designed for scenarios like assembly analysis, code generation, and diagnostics tools.
Summary
The System.Reflection.Metadata
namespace offers a powerful and efficient way to read and write the metadata structures of .NET assemblies, including types, methods, fields, properties, events, and their associated attributes and signatures. Unlike higher-level reflection APIs, this namespace operates directly on the Portable Executable (PE) file format, providing granular control and performance benefits.
Key Concepts
- MetadataReader: The primary entry point for reading metadata from an assembly.
- MetadataBuilder: Used to create and modify metadata.
- Entity Handle: Represents a reference to a metadata entity (e.g.,
TypeDefinitionHandle
,MethodDefinitionHandle
). - RowId: A unique identifier for a row within a metadata table.
- String, GUID, Blob: Structures for accessing string literals, GUIDs, and binary blobs stored in the metadata.
Classes
Class | Description |
---|---|
MetadataReader | Represents a reader for the metadata of a .NET assembly. |
MetadataBuilder | Represents a builder for .NET assembly metadata. |
EntityHandle | Represents a handle to a metadata entity. |
TypeDefinition | Represents a type definition in the metadata. |
MethodDefinition | Represents a method definition in the metadata. |
Parameter | Represents a parameter of a method. |
FieldDefinition | Represents a field definition. |
PropertyDefinition | Represents a property definition. |
EventDefinition | Represents an event definition. |
Example Usage
The following C# code snippet demonstrates how to read type names from an assembly using MetadataReader
:
using System;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.IO;
// Load the assembly metadata
using (var stream = File.OpenRead("YourAssembly.dll"))
using (var peReader = new PEReader(stream))
{
MetadataReader metadataReader = peReader.GetMetadataReader();
Console.WriteLine("Types in the assembly:");
foreach (var typeHandle in metadataReader.TypeDefinitions)
{
TypeDefinition typeDefinition = metadataReader.GetTypeDefinition(typeHandle);
string typeName = metadataReader.GetString(metadataReader.GetTypeDefinition(typeHandle).Name);
Console.WriteLine($"- {typeName}");
}
}