Some helpful stuff to use embedded resources with dotnet.
- Add the csMACnz.EmbedRes NuGet package to your project.
- Create a folder in your project to hold your resource text files (e.g.
MyResources
). - Add text files to your resource folder (e.g.
Resource1.txt
,Resource2.sql
). - Create a
.cs
file to match the name of the resource folder. - Add the following code to your cs file:
public static class MyResources
{
public static string Resource1 => GetFileContents("Resource1.txt");
public static string Resource2 => GetFileContents("Resource2.sql");
public static string GetFileContents(string resourceName)
{
return ResourceLoader.GetContentFromFolderMatchingTypeName<MyResources>(resourceName);
}
}
- Make sure you embed your resources by the following in your csproj:
<Project Sdk="Microsoft.NET.Sdk">
...
<ItemGroup>
<EmbeddedResource Include="MyResources\Resource1.txt" />
<EmbeddedResource Include="MyResources\Resource2.sql" />
</ItemGroup>
...
</Project>
If you are comfortable with the above, try using these helpers for more 'magic' (a.k.a convention):
public static class MyResources
{
public static string Resource1 => GetTextContents();
public static string Resource2 => GetSqlContents();
public static string GetTextContents([CallerMemberName] string resourceName = null)
{
return GetFileContents($"{resourceName}.txt");
}
public static string GetSqlContents([CallerMemberName] string resourceName = null)
{
return GetFileContents($"{resourceName}.sql");
}
// This can be much simpler if you only have one filetype/extension
public static string GetFileContents(string resourceName)
{
return ResourceLoader.GetContentFromFolderMatchingTypeName<MyResources>(resourceName);
}
}