Skip to content

6over3/Embed.Generator

Repository files navigation

Embed.Generator

A C# source generator that embeds files directly into your assembly at compile time, inspired by C23's #embed directive.

Features

  • 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

Installation

dotnet add package Embed.Generator

Usage

1. Mark a class with [ResourceDictionary]

using 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; }
}

2. Add files as AdditionalFiles in your .csproj

<ItemGroup>
    <AdditionalFiles Include="Resources\**\*" />
</ItemGroup>

3. Build and use

// 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);
}

Configuration

Text vs Binary Files

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; }

Dictionary Metadata

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;

Requirements

  • .NET 9.0 or later (for ReadOnlySpan<byte> properties)
  • C# 13.0 or later (for partial properties)

Diagnostics

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

Examples

See the sample project for a complete example.

License

MIT License - see LICENSE file for details.

About

C23-style embed source generator for C#

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages