Jack
Jack

Reputation: 3799

Loop through Visual Studio resources

I'm using Visual Studio 2010 with a C# WPF app and I've added some images into a subfolder called assets. Is there any way I can loop through all the images that i've added to the folder using pack URIs or something similar?

Upvotes: 1

Views: 1618

Answers (1)

brunnerh
brunnerh

Reputation: 184692

The following method gets all the file names in a resource-folder:

public static string[] GetResourcesUnder(string folder)
{
    folder = folder.ToLower() + "/";

    var assembly       = Assembly.GetCallingAssembly();
    var resourcesName  = assembly.GetName().Name + ".g.resources";
    var stream         = assembly.GetManifestResourceStream(resourcesName);
    var resourceReader = new ResourceReader(stream);

    var resources =
        from p in resourceReader.OfType<DictionaryEntry>()
        let theme = (string)p.Key
        where theme.StartsWith(folder)
        select theme.Substring(folder.Length);

    return resources.ToArray();
}

Just need to put the head back on when you use them:

var files = GetResourcesUnder("Images");
foreach (var file in files)
{
    string uriPath = "pack://application:,,,/Images/" + file;
    //...
}

I did not write this method, it's from another question here on SO, i'll try to find it...

Edit: It's from here.

Upvotes: 1

Related Questions