RSM
RSM

Reputation: 15118

dynamically load resource file

I want to dynamically load a resource file.

If i do it statically, it obviously works well:

System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources._88);
player.Play();

This loads and plays the resource _88.

However, I want this to be dynamically,

I have a variable 'num' which can be any number from 1-90, and i want to load the resource related to that number.

So I create another variable called 'soundURL' which looks like:

var soundURL = "_" + num;

But when I use that with the previous it obviously doesnt work:

System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.soundURL);

How can I overcome this?

Upvotes: 6

Views: 5092

Answers (3)

terrybozzio
terrybozzio

Reputation: 4532

This will do it:

    string file = "_" + num;

    SoundPlayer sp;
    Stream s = Properties.Resources.ResourceManager.GetStream(file);
    if (s != null)
    {
        sp = new System.Media.SoundPlayer(s);
        sp.Play();
    }

Upvotes: 1

Original10
Original10

Reputation: 572

You can use the ResourceManager to load resources by name

object O = Properties.Resources.ResourceManager.GetObject("_88");

You then just need to cast it as a Stream..

var s = (Stream)O;
System.Media.SoundPlayer player = new System.Media.SoundPlayer(s);
player.Play();

Upvotes: 5

Jurica Smircic
Jurica Smircic

Reputation: 6445

If that's a resx resource file, you can get the resource value using ResourceManager

var soundURL=Properties.Resources.ResourceManager.GetString("_" + num);

Upvotes: 2

Related Questions