Search code examples
c#csvstreamresourcesstreamreader

Get Stream from Properties.Resources in Visual Studio 2013


I have seen lots of posts outthere regarding this and could not get any to work. I added a file to Resources folder of my project (right click on project->Properties->Resources, then select File, Add File).

I tried setting Build Action to both Resources and Embedded Resources.

I need to read that file using StreamReader.

I have tried following but both return NULL for myStream regardless whether I set Build Action to Resources or Embedded Resource:

    // IF I ADD FILE AS SUGGESTED BELOW IN UPDATE, THIS WILL WORK; OTHERWISE, I GET NULL   
    Stream myStream = Assembly
      .GetExecutingAssembly()
      .GetManifestResourceStream("MyProject.General.Tests.mytestfile.csv"); //returns NULL
    using (CsvReader csv = new CsvReader(new StreamReader(myStream), true)
    {
       ... 
    }

I have also tried this but it also returns NULL

Stream myStream = Assembly
  .GetExecutingAssembly()
  .GetManifestResourceStream(Properties.Resources.mytestfile); //returns NULL
using (CsvReader csv = new CsvReader(new StreamReader(myStream), true)
{
   ...
}

If I go to quick watch and type this Properties.Resources.mytestfile, I do get string representation of my file back.

UPDATE, INSTEAD OF ADDING THE FILE BY RIGHT CLICKING ON PROJECT->PROPERTIES->RESOURCES (THIS WAY, IT WILL NOT WORK), ADD IT BY RIGHT CLICKING ON PROJECT->ADD->EXISTING ITEM, THEN SET BUILD ACTION=EMBEDDED RESOURCE, IT WILL WORK. (Thanks to Aedvald Tseh for his detailed answer that helped me figure this)


Solution

  • Add your csv-file as embedded resource to the studio project. csv file as embedded resource

    Prefix the name of your file with default namespace of your visual studio project. Thus "mytestfile.csv" is turned into "ConsoleApp1.mytestfile.csv". Then you can read the content like so:

    System.IO.Stream myStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApp1.mytestfile.csv");