views:

66

answers:

2

In short my program plays a random embedded audio file when a timer runs out, is there a way to refer to the my.resources files as an array and use them that way rather than needing to know the exact file name of the resource?

+2  A: 

I have not tried this on a windows application, but I had to do the same thing for a web application, and I used the following code to achieve that:

VB version:

' get a reference to the current assembly
Dim a = Assembly.GetExecutingAssembly()

' get a list of resource names from the manifest
Dim resNames = a.GetManifestResourceNames()

'Generate a random number
Dim randomNumber = YourRandomNumberGenerator()

'Get the file name using the randomNumber
Dim randomFileNameFromResource = resNames(randomNumber)

'Get the contents of the file:
Dim sr = New StreamReader(a.GetManifestResourceStream(randomFileNameFromResource))
Dim fileContent = sr.ReadToEnd()

C# version

        // get a reference to the current assembly
        var a = Assembly.GetExecutingAssembly();

        // get a list of resource names from the manifest
        var resNames = a.GetManifestResourceNames();

        //Generate a random number
        var randomNumber = YourRandomNumberGenerator();

        //Get the file name using the randomNumber
        var randomFileNameFromResource = resNames[randomNumber];

        //Get the contents of the file:
        var sr = new StreamReader(
              a.GetManifestResourceStream(randomFileNameFromResource ));
        var fileContent = sr.ReadToEnd();

I would think the position of the file in the array would change over time though if more embedded resources get added, but i guess it would not matter for you since you are picking a random one anyway.

Roberto Sebestyen
Assembly, doesn't appear to exist directly in vb2005, however i found it i think My.Application.Info.LoadedAssemblies(0).GetFiles there, so you weren't too far off
Jim
Ah OK thanks, I was using it on .NET Framework v3.5
Roberto Sebestyen
A: 

the correct answer for me in vb2005 is Reflection.Assembly.GetExecutingAssembly.GetManifestResourceNames() theres also a get stream function in there, thank you Roberto for that

Jim