Search code examples
c#.netresourcesresx

Storing Datasets in a RESX file


I'm very new to resources in C# / .Net files.

I need to store a table of operational data in a resource file (*.RESX), and cannot figure out how to do it.

If I were to do it hardcoded in C, I'd do it like this:

struct {
   int inputA;
   int outputB;
} dataPoint;

dataPoint myOpsData[] = { { 0,  2000},
                          {10,  4000},
                          {20,  6300},
                          {30,  8400},
                          {40, 10620} };

The most straightforward in the Visual Studio 2010 editor is with Strings, but that only maps a string to a value. If I were to do this, my dataset would look something like:

Name:       Value:
-----       ------
PerfData1   { 0,  2000}
PerfData2   {10,  4000}
PerfData3   {20,  6300}
PerfData4   {30,  8400}
PerfData5   {40, 10620}

But this format would require a lot of parsing and associated validation and error handling that just seems unnecessary.

How can I represent arrays of data-points (or even more complex data-types) in a .RESX resource file?


Solution

  • You don't have to use a ResX to embed some static data in an assembly.

    With Visual Studio, you can just add the file (Add a New Item or Add an Existing Item), change the Build Action (F4 or Properties Window) to "Embedded Resource", and you can then load it with a piece of code like this (NOTE: should be in the same assembly to avoid security issues):

    using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApplication1.MyFile.MyExt"))
    {
       // load data from stream
    }
    

    I suppose here the file is MyFile.MyExt, and this file is directly added to the project root, as VS automatically adds the current project namespace - here ConsoleApplication1 - to embedded resources path.

    If you are unsure about this path, I suggest you use a tool such as .NET reflector that is capable of displaying embedded resources names and data from an assembly.

    This will get you a Stream instance. So you can store any kind of data provided you can load/save it from/to a Stream instance (MemoryStream, StreamReader, DataSets, .NET or Xml serialized objects, Bitmaps, etc.)