Thursday, 4 November 2010

Visual Studio: Adding and using resource files

Sometimes you may want to include some existing files in your Visual Studio Project as project resources e.g. some text files that you would like to read from. This makes much easier to read their content from your code without manually working with streams etc. You can do that by following a few simple steps:
  1. Open Resource editor
    To do that right click on your project and choose "Properties" option. When the properties screen opens choose "Resources" tab: Visual Studio: Project Reources TabIf you haven't defined any resources before you'll be asked if you'd like to create a default Resource file for that project: "This project does not contain a default resource file. Click here to create one".

  2. Creat resource file
    When you confirm to do that the default resource file is created (see file marked on picture below) you can now choose to add a new file as resource: Visual Studio: Adding file as resource

  3. Add file as resource
    After you select the file it's available as resource. In my sample project I selected text file "test.txt". It also appeared in solution explorer (marked with red): Visual Studio: File declared as resource

  4. Access file content from code
    After you save all the changes you made to resources you can access the file content from your code simply by using its name:
    using SampleProject.Properties;
    ...
    string fileContent = Resources.test;

    You have to admit it's much easier then manually opening and reading from files.

5 comments:

Matthew said...

How would one do this in a c++ console application? I have a .txt file i want to add as a resource instead of using fopen.

Filip Czaja said...

Matthew,
If you have a VS project created for that console app adding resources should work exactly the same way.
F.

Dennis B. D. said...

Good & helpful article, thanks. BTW, in a localized app, it appears each language's resource file must be created manually and correctly named (VS2010).

Guigs said...

Great article, very useful

jesus R said...

Hi everyone, first im sorry for my bad english, i speak spanish..

Hi I need help,
I wanna add to my project a text file.
I do it with Resources

how read the text file and load in a array

something like this:

FileOpen(1, "my.resources.adasdad.txt, OpenMode.Input)
xfil = 1
While Not EOF(1)

For h = 1 To 7
Input(1, tabla(xfil, h))
Next
xfil = xfil + 1
End While

FileClose(1)

i am using visual studio 2010.