A C# source generator that embeds files directly into your assembly at compile time, inspired by C23's #embed directive.
- Embed files as
ReadOnlySpan<byte>properties - Zero runtime I/O overhead
- Type-safe access to embedded resources
- Automatic path-based lookups
- Metadata about embedded files
- Support for both text and binary files
dotnet add package Embed.Generatorusing System;
using Embed;
[ResourceDictionary]
public static partial class EmbeddedResources
{
[Embed("Resources/config.json")]
public static partial ReadOnlySpan<byte> Config { get; }
[Embed("Resources/logo.png")]
public static partial ReadOnlySpan<byte> Logo { get; }
}<ItemGroup>
<AdditionalFiles Include="Resources\**\*" />
</ItemGroup>// Direct access
var configBytes = EmbeddedResources.Config;
var configText = Encoding.UTF8.GetString(configBytes);
// Lookup by path
var logoBytes = EmbeddedResources.GetResource("Resources/logo.png");
// Get metadata
if (EmbeddedResources.Metadata.TryGetInfo("Config", out var info))
{
Console.WriteLine($"Size: {info.Size} bytes");
Console.WriteLine($"IsText: {info.IsText}");
}
// List all embedded files
foreach (var path in EmbeddedResources.GetAllPaths())
{
Console.WriteLine(path);
}The generator auto-detects text files by extension (.txt, .json, .xml, .cs, etc.). You can override this:
[Embed("Resources/data.bin", IsText = true)] // Force text
public static partial ReadOnlySpan<byte> Data { get; }
[Embed("Resources/file.txt", IsText = false)] // Force binary
public static partial ReadOnlySpan<byte> Binary { get; }Add metadata to your resource dictionary:
[ResourceDictionary(Locale = "en-US", Description = "Application resources")]
public partial static class EmbeddedResources
{
// ...
}
// Access metadata
var locale = EmbeddedResources.DictionaryMetadata.Locale;
var description = EmbeddedResources.DictionaryMetadata.Description;- .NET 9.0 or later (for
ReadOnlySpan<byte>properties) - C# 13.0 or later (for partial properties)
| Code | Description |
|---|---|
| EMB001 | File not found in AdditionalFiles |
| EMB002 | Error reading file |
| EMB003 | [ResourceDictionary] must be on partial static class |
| EMB004 | [Embed] must be on partial static property |
| EMB005 | [Embed] property must return ReadOnlySpan |
See the sample project for a complete example.
MIT License - see LICENSE file for details.