1

Take a look at this simple console application:

enter image description here

I am so curios on how I am able to get the contents of TextFile1.txt if its build action is set to none:

enter image description here

How can I read the contents of TextFile1.txt withtout using Resources.resx? I know how to do it if I set the build action to embedded resource. But how do you do it when its build action is set to none? In other words I want to know how Resource1.resx is able to get the contents of TextFile1.txt.

Tono Nam
  • 34,064
  • 78
  • 298
  • 470
  • You won't be able to, if you set it to `None`. Because if you do, the resource is excluded from compiling. [More details](https://stackoverflow.com/a/145769/302248). – Sach Aug 25 '17 at 16:15
  • @Sach the question "how Resource1.resx is able to get the contents of TextFile1.txt." still stands. When you add a resource to a .resx file, it will create a folder in solution called "Resources" and there you have your file with ``Build Action`` ``None``, so how does ``Resource1.resx`` do it? – Rand Random Aug 25 '17 at 16:21
  • You could just look into the ``Resource1.Designer.cs`` code and figure out how its working. In my case tried it with an Image and it produced the following code ``internal static System.Drawing.Bitmap Image1 { get { object obj = ResourceManager.GetObject("Image1", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } }`` - now go and follow the bunny into the hole – Rand Random Aug 25 '17 at 16:24
  • @RandRandom well I guess that makes sense, but there are two questions that sounds like opposites. One, _how can I read the text file without Resources.resx_ and the other, _how does Resources.resx read the file_. – Sach Aug 25 '17 at 16:29

1 Answers1

3

Short answer: you cannot do what resx does, because a special "toolchain magic" is required to support this.

Visual Studio has special processing for embedding resources referenced by resx files.

Resource resx files use XML syntax to describe what goes into the resource. If you open the file in text editor, you should see something like this:

<data name="TextFile1" type="System.Resources.ResXFileRef, System.Windows.Forms">
    <value>textfile1.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data>

When you compile your project, this file is processed by a custom tool set for your resx file, ResXFileCodeGenerator. When it sees data nodes of ResXFileRef type, it reads the content of TextFile1.txt, and embeds it into the compiled version of Resource1.

The tool ignores None/Do not copy settings on the file itself. In fact, if you set Build Action property to "Embed resource", the content of the file would be embedded twice.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523