Embedded Resources with .Net Core

Tags: ASP.NET, .Net Core

I was writing some tests today and had a need to use an embedded resource as I did not want to have huge strings inside my test methods.  The embedded resource file is compiled along with the assembly.  Cool!

In .Net Core you have to indicate the presence of an embedded resource in your project.json file.   Here's how that looks:


	"buildOptions": {
		"embed": [ "exampleFile.txt" ]
	}

The exampleFile in this case contained some json.   I created a method to read from the file and return its contents. Here's the code:


public static string GetEmbeddedResource(string resourceFileName, AssemblyName assemblyName)
	{
		var resourceName = Assembly.Load(assemblyName).GetManifestResourceNames()
                            .Where(r => r.Contains(resourceFileName)).First();
		var resource = Assembly.Load(assemblyName).GetManifestResourceStream(resourceName);
		string fileContents = "";
		using (MemoryStream ms = new MemoryStream())
		{
			resource.CopyTo(ms);
			fileContents = UTF8Encoding.UTF8.GetString(ms.ToArray());
		}
	
		return fileContents;
	}

The method takes the assembly name and loads the embedded resource names, then finds the resource you are looking for and streams it into a string.  Handly.

Embedded resources are useful in test classes when you want to serialize test data and have it in a nice human readable file; and you don't have to mess around with the paths to the file when accessing the data.

No Comments

Add a Comment