Raymond Raymond

Read Embedded Assembly Resource Files in .NET

event 2021-08-13 visibility 9,994 comment 0 insights toc
more_vert
insights Stats

In .NET, resource file (.resx) is used to store assembly required resources like string, images or other binary resources. When compiling the project, these resource files will be embedded into the assembly (*.dll). One typical usage of resource file in .NET Core is to store localized string for UIs. This article will mainly talk about other embedded files like JSON and how to read them.

A little bit more about *.resx

To utilize string sources in .resx files, we can utilize class IStringLocalizer<T>.Type T is the resource type. In .NET call, string localizer can be instantiated directly using built-in dependency injection.

Example code

The following code snippet injects an instance of IStringLocalizer<T> for the controller. 

public class MyController : ControllerBase
{
	private readonly ILogger<MyController> logger;
	private readonly IStringLocalizer<SharedResource> stringLocalizer;

	public MyController(ILogger<MyController> logger, IStringLocalizer<SharedResource> stringLocalizer)
	{
		this.logger = logger;
		this.stringLocalizer = stringLocalizer;
	}
	
	//...
}

Variable stringLocalizer can be then used to read string sources from SharedResource.resx or its localized versions.

var title = stringLocalizer["KEY_TITLE"];

The above code snippet reads string resource with key KEY_TITLE from the resource file.

Create other resource files 

To create other embedded files, simply set the Build Action of the resource file property as Embedded resource via Visual Studio.

20210813122823-image.png

Alternatively, open project file in a text editor and added the following line:

<ItemGroup>
    <EmbeddedResource Include="Templates\templates.json" />
</ItemGroup>

The above code snippet adds file templates.json in folder Templates as embedded resource for the project.

Read embedded resource file

To read embedded resource file, we can use Assembly.GetManifestResourceStream API. 

The following helper class provides two functions: one return a Stream object and another returns the resource file content as a string.

/// <summary>
    /// Helper class to read embedded resources in assembly.
    /// </summary>
    public static class ResourceHelper
    {
        /// <summary>
        /// Read embedded resource as Stream.
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="folder"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static Stream ReadResource(Assembly assembly, string folder, string fileName)
        {
            string resourcePath;
            var assemblyName = assembly.GetName().Name;
            if (folder != null)
                resourcePath = $"{assemblyName}.{folder}.{fileName}";
            else
                resourcePath = $"{assemblyName}.{fileName}";

            return assembly.GetManifestResourceStream(resourcePath);
        }

        /// <summary>
        /// Read embedded resource as String.
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="folder"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string ReadResourceAsString(Assembly assembly, string folder, string fileName)
        {
            using var stream = ReadResource(assembly, folder, fileName);
            if (stream == null)
                return null;
            using var streamReader = new StreamReader(stream);
            return streamReader.ReadToEnd();
        }
    }

About resource file in a folder

As shown in the above code, the path for resource file in a folder needs to be concatenated using '.' :

resourcePath = $"{assemblyName}.{folder}.{fileName}";

The path is case-sensitive. If the file name includes character '.' (excluding the extension part), the method will return null. Thus please ensure there is no '.' in your resource file name.

References

Assembly.GetManifestResourceStream Method (System.Reflection) | Microsoft Docs

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts