How to Embed a Text File in a .Net Assembly

How to embed a text file in a .NET assembly?

Right-click the project file, select Properties.

In the window that opens, go to the Resources tab, and if it has just a blue link in the middle of the tab-page, click it, to create a new resource.

Sample Image

Then from the toolbar above the tab-page, select to add a new text file, give it a name, it will be added to your project and opened up.

If you get this far, then in your code you can type in Resources.TheNameYouGaveTheTextFileHere and you can access its contents. Note that the first time you use the Resources class in a class, you need to add a using directive (hit Ctrl+. after typing Resources to get the menu to get VS to do it for you).

If something was unclear about the above description, please leave a comment and I'll edit it until it is complete or makes sense :)

Embed Text Files in a .NET Assembly or Executable

With text files you can also proceed as following:

  1. Double click your Properties -> Resources.resx file to open the resource designer.
  2. From the first small drop down on the top, select "Files" as resource type.
  3. Click on Add Resource -> Add Existing File... and select your text files.

Let's say that the TXT you added was called Foo.txt... you can just access it's content like so:

String foo = Properties.Resources.Foo;

Then you can also change te file names inside the resource designer and they will be automatically refactored in your code. From the Resources directory, where they are now located in your project, you can also edit them.
I just recommend you to keep their access level as internal.

Embed Text File in Resources

Add the text file to your project, then define it as content (Build Action=Content) and Copy always to Output.

If you have an installer for your project (standard installer) you can setup the file system so the installer will copy the text file automatically.

to get the folder where the application is running, i use this :

Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location);

If you're using the new installer (ClicOnce) i cannot help you, but i wish you luck :=)

How to read embedded resource text file

You can use the Assembly.GetManifestResourceStream Method:

  1. Add the following usings

    using System.IO;
    using System.Reflection;
  2. Set property of relevant file:

    Parameter Build Action with value Embedded Resource

  3. Use the following code

    var assembly = Assembly.GetExecutingAssembly();
    var resourceName = "MyCompany.MyProduct.MyFile.txt";

    using (Stream stream = assembly.GetManifestResourceStream(resourceName))
    using (StreamReader reader = new StreamReader(stream))
    {
    string result = reader.ReadToEnd();
    }

    resourceName is the name of one of the resources embedded in assembly.
    For example, if you embed a text file named "MyFile.txt" that is placed in the root of a project with default namespace "MyCompany.MyProduct", then resourceName is "MyCompany.MyProduct.MyFile.txt".
    You can get a list of all resources in an assembly using the Assembly.GetManifestResourceNames Method.


A no brainer astute to get the resourceName from the file name only (by pass the namespace stuff):

string resourceName = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith("YourFileName.txt"));

A complete example:

public string ReadResource(string name)
{
// Determine path
var assembly = Assembly.GetExecutingAssembly();
string resourcePath = name;
// Format: "{Namespace}.{Folder}.{filename}.{Extension}"
if (!name.StartsWith(nameof(SignificantDrawerCompiler)))
{
resourcePath = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith(name));
}

using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}

How to merge a text file and embed it in C# code build

try this :

Add file to Resources.resx
Open up the Resources.resx file, use the dropdown box to add the file, set Access Modifier to public.
Sample Image

then you can get text if file like that:

string text = Properties.Resources.vaCommands;

Can I embed a file in a .NET Core executable and read it at runtime?

The solution is similar to this answer, just slightly different for VS Mac and .NET Core 3.1.

I achieved what I was looking for by adding the files to my C# project, then setting their build action to 'Embedded Resource'. It's here in VS for Mac 2019:

EmbeddedResource in VS Mac

To read them, the syntax (assuming you're in a class within the same project as the files) is:

var assembly = typeof(MyClass).Assembly;
Stream myFile = assembly.GetManifestResourceStream("MyProject.MyFolder.MyFile.json");

// To get the text as a string
var sR = new StreamReader(myFile);
var myFilesText = sR.ReadToEnd();
sR.Close();

If you're not sure what their names are, you can list the resources with:

string[] names = assembly.GetManifestResourceNames();

Is it possible to embed binary data in a .NET assembly

Yes. If you are using resources, you can include files too, which are represented as a byte array. Else you can include a file and set the Build Action to Embedded Resource, which include it as a resource too, which you can manually read.

public byte[] ExtractResource(Assembly assembly, string resourceName)
{
if (assembly == null)
{
return null;
}

using (Stream resFilestream = assembly.GetManifestResourceStream(resourceName))
{
if (resFilestream == null)
{
return null;
}

byte[] bytes = new byte[resFilestream.Length];
resFilestream.Read(bytes, 0, bytes.Length);

return bytes;
}
}

Then use it like this:

byte[] bytes = this.ExtractResource( Assembly.GetExecutingAssembly()
, "Project.Namespace.NameOfFile.ext"
);

Reading from a text file resource which is compiled into a .NET assembly

My final solution:

class Program
{
static void Main(string[] args)
{
Stream stream = typeof(Program).Assembly.GetManifestResourceStream("TheNameOfMyProject.TheNameOfSubFolder.file.txt");
StreamReader sr = new StreamReader(stream);
var content = sr.ReadToEnd();
Console.WriteLine(content);
Console.ReadLine();
}
}

C# application can not load embedded text resources

I fixed it by using this code, it loops trough all resources and chooses that one i want:

string[] resNames = Assembly.GetExecutingAssembly().GetManifestResourceNames();
foreach (string resName in resNames)
{
if (resName == ("Resource1.txt"))
{
Assembly assembly = Assembly.GetExecutingAssembly();
string resourcename = assembly.GetManifestResourceNames().Single(str => str.EndsWith(resName));
Stream stream = assembly.GetManifestResourceStream(resourcename);
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
string output = reader.ReadToEnd();
reader.Dispose();
stream.Dispose();
}
}

How to use a Embedded file from Assembly for SoundPlayer contexts inside of a C# application

I finaly figured it out, so I am answering my own question in the hopes that people who are struggling in the future can figure it out.

Using the link provided by @Jimi for Accessing Resources in SharpDevelop, and scrolling down to the "Embedding Files directly" section, shows the context at which to access Embedded Resource. The thing to note here is that the return type of GetManifestStream(string) is a System.IO.Stream object.
This is important as we need SoundPlayer to accept a System.IO.Stream object some how. This can be done two ways, by using an overloaded constructor or Property of the SoundPlayer class. As defined by the MSDN page for the SoundPlayer Class.

However, when I tested this, I could not get the sound to play. Furthering my research, I found that Assembly.GetExecutingAssembly() has a accessible method named "GetManifestResourceNames()" that returns a string array of all the resources and their corrective names to access them. I was able to see the return by creating a Windows Form Label called "ExecutingAssem", and using the instructions from DotNetPerls to create a static method named "ConvertStringArrayToStringJoin()", but changing its seperator from "." to "|" to better read the assets.

With that in place the final program shows the list of embedded resources with the line:
ExecutingAssem.Text=ConvertStringArrayToStringJoin(Assembly.GetExecutingAssembly().GetManifestResourceNames());

And the final program appearing as:
Program showing all the resources in the corner

The interesting thing here is that the song resource (Resonance) is not actually a part of the Namespace, or MainForm...but rather its own name as the resource title.

With that missing information found, I needed to change the program from reading the drive to reading the manifest stream. Using the overloaded constructor that utilizes a System.IO.Stream object as a parameter instead of a string to a file location, I changed where the player object is initiated to use that constructor.

SoundPlayer player =new SoundPlayer(Assembly.GetExecutingAssembly().GetManifestResourceStream("Resonance"));

Finally the final application played the song with the ability to move the .exe file elsewhere and still be able to play the same song without "Resonance.wav" needing to be in the same directory.



Related Topics



Leave a reply



Submit