开发者

How to enumerate images included as "Content" in the XAP?

开发者 https://www.devze.com 2023-04-05 08:34 出处:网络
I\'m including a number of images as \"Content\" in my deployed XAP for Mango. I\'d like to enumerate these at runtime - is there a开发者_如何学Cny way to do this?

I'm including a number of images as "Content" in my deployed XAP for Mango.

I'd like to enumerate these at runtime - is there a开发者_如何学Cny way to do this?

I've tried enumerating resources like:

foreach (string key in Application.Current.Resources.Keys)
{
    Debug.WriteLine("Resource:" + key);
}

But the images aren't included in the list. I've also tried using embedded resources instead - but that didn't help. I can read the streams using Application.GetResourceStream(uri) but obviously I need to know the names in order to do this.


This is no API baked in to WP7 that allows you to enumerate the contents of the Xap. You need to know the name of the content items before you can retreive them.

There probably is some code floating around somewhere that is able to sniff out the Zip catalog in the XAP however I would strongly recommend that you don't bother. Instead include some sensible resource such as an Xml file or ResourceDictionary that lists them.


Having found no practical way to read the Content files from a XAP I build such a list at design time using T4.

See an example at https://github.com/mrlacey/phonegap-wp7/blob/master/WP7Gap/WP7Gap/MainPage.xaml.cs

This seems the right way to go as:
a) I'd rather build the list once at design time rather than on every phone which needs the code.
and
b) I shouldn't ever be building the XAP without being certain about what files I'm including anyway.

Plus it's a manual step to set the build action on all such files so adding a manual step to "Run Custom Tool" once for each build isn't an issue for me.


There is no way to enumerate the files set as "Content".

However, there is a way to enumerate files at runtime, if you set your files as "Embedded Resource".

Here is how you can do this:

  1. Set the Build Action of your images as "Embedded Resource".
  2. Use Assembly.GetCallingAssembly().GetManifestResourceNames() to enumerate the resources names
  3. Use Assembly.GetCallingAssembly().GetManifestResourceStream(resName) to get the file streams.

Here is the code:

    public void Test()
    {
        foreach (String resName in GetResourcesNames())
        {
            Stream s = GetStreamFromEmbeddedResource(resName);
        }
    }

    string[] GetResourcesNames()
    {
        return Assembly.GetCallingAssembly().GetManifestResourceNames();
    }

    Stream GetStreamFromEmbeddedResource(string resName)
    {
        return Assembly.GetCallingAssembly().GetManifestResourceStream(resName);
    }

EDIT : As quetzalcoatl noted, the drawback of this solution is that images are embedded in the DLL, so if you a high volume of images, the app load time might take a hit.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号