Wednesday, March 5, 2014

Accessing a file from a resource

This is really simple, just I need to remember these little rules to get it to work. First the code of reading a text file from a resource looks like this:
         List<String> lines = new List<String>();
         var assembly = Assembly.GetExecutingAssembly();
         var stream = assembly.GetManifestResourceStream("MyNamepace.Resources.MyFile.txt");
         var textStreamReader = new StreamReader(stream);

         while (!textStreamReader.EndOfStream)

Here are few points:

  • You can add the resource using the visual resource designer in your project properties
  • The resource id is the your project name space + any folder names it might be under (normally under a folder called Resource)
  • Make sure the file is an embedded resource, by right clicking on the file you can change its build actions

No comments: