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.