Random programming things I'd want to remember

Wednesday, December 28, 2011

Get Stream for a BinaryReader for a file embedded in exe


public Stream GetDataFileStream(string resourceName)
  {
    foreach (string currentResource in System.Reflection.Assembly.
        GetExecutingAssembly().GetManifestResourceNames())
      if (currentResource.LastIndexOf(resourceName) != -1)
        {
          return System.Reflection.Assembly.GetExecutingAssembly().
            GetManifestResourceStream(currentResource);
        }

        throw new Exception("Resource not found : " + resourceName);
  }


//Then call this code:

using (BinaryReader reader = new BinaryReader(GetDataFileStream("data.dat")))
  {
    yourDataContainter = reader.ReadOrWhatever();
  }

In solution explorer, right-click on the text file that you want to embed, select "Properties". Under "Build Action", select "Embedded Resource", build solution.

No comments: