Embed Directive in C#
Here’s the translation of the Go code to C# with explanations in Markdown format suitable for Hugo:
Our first program demonstrates how to embed files and folders into the compiled binary at build time. This is achieved using attributes in C#.
using System;
using System.Reflection;
using System.IO;
public class EmbedExample
{
// Embed a single file as a string
[EmbeddedResource("folder.single_file.txt")]
private static string fileString;
// Embed a single file as a byte array
[EmbeddedResource("folder.single_file.txt")]
private static byte[] fileByte;
// Embed multiple files
[EmbeddedResource("folder.file1.hash")]
[EmbeddedResource("folder.file2.hash")]
private static Assembly assembly;
public static void Main()
{
// Print out the contents of 'single_file.txt'
Console.Write(fileString);
Console.Write(System.Text.Encoding.UTF8.GetString(fileByte));
// Retrieve some files from the embedded resources
using (Stream stream = assembly.GetManifestResourceStream("folder.file1.hash"))
using (StreamReader reader = new StreamReader(stream))
{
string content1 = reader.ReadToEnd();
Console.Write(content1);
}
using (Stream stream = assembly.GetManifestResourceStream("folder.file2.hash"))
using (StreamReader reader = new StreamReader(stream))
{
string content2 = reader.ReadToEnd();
Console.Write(content2);
}
}
}
In C#, we use the EmbeddedResource
attribute to embed files into the assembly. This is similar to the //go:embed
directive in the original example.
To embed a file as a string or byte array, we use the EmbeddedResource
attribute on static fields. The attribute takes the path to the file as an argument.
For embedding multiple files, we can use multiple EmbeddedResource
attributes on a static Assembly
field. We then use GetManifestResourceStream
to access these embedded files at runtime.
To run this example, you need to create the following folder structure and files:
$ mkdir -p folder
$ echo "hello c#" > folder/single_file.txt
$ echo "123" > folder/file1.hash
$ echo "456" > folder/file2.hash
Then compile and run the program:
$ csc EmbedExample.cs
$ mono EmbedExample.exe
hello c#
hello c#
123
456
Note that the exact commands may vary depending on your C# development environment. If you’re using .NET Core or .NET 5+, you might use dotnet build
and dotnet run
instead.
This example demonstrates how to embed files into your C# application, which can be useful for including configuration files, templates, or other resources directly in your executable.