如何列出目录包URI的每个资源文件?

时间:2010-10-15 09:09:56

标签: c# wpf visual-studio uri

我有许多XML文件,其中“Build Action”设置为“Resource”。我可以使用众所周知的包URI方案从代码中访问它们,或者只是一个相对URI(实际上是一个有效的包URI,如Microsoft在包装URI msdn页面中所述,所以一切都是包uri:p),就像这个:

Uri uri1 = new Uri("pack://application:,,,/someFolder/myResource1.xml");
Uri uri2 = new Uri("someFolder/myResource2.xml");

实际上,我需要从每个xml文件中获取一个流。我能做的是以下几点:

Uri uri1 = new Uri("pack://application:,,,/someFolder/myResource1.xml");
var stream1 = App.GetResourceStream(uri1).Stream; // works fine

它工作正常,我得到我的溪流。现在我的问题是:

如果我不知道我的资源名称怎么办?(只有“someFolder”的路径)
如何列出?

我无法使用Directory.GetFiles,因为资源已嵌入到程序集中。一种可能的解决方案是将我的资源的构建操作设置为“嵌入式资源”,然后使用assembly.GetManifestResourceNames()函数,但我很顽固,不想更改此构建操作:p

谢谢!

编辑:我来的是这样的:

    /// <summary>
    /// Returns a dictionary of the assembly resources (not embedded).
    /// </summary>
    /// <param name="filter">A regex filter for the resource paths.</param>
    public static IDictionary<string, object> GetResources(string filter) {
        var asm = Assembly.GetEntryAssembly();
        string resName = asm.GetName().Name + ".g.resources";
        Stream stream = asm.GetManifestResourceStream(resName);
        ResourceReader reader = new ResourceReader(stream);

        IDictionary<string, object> ret = new Dictionary<string, object>();
        foreach (DictionaryEntry res in reader) {
            string path = (string)res.Key;
            if (Regex.IsMatch(path, filter))
                ret.Add(path, res.Value);
        }
        return ret;
    }

0 个答案:

没有答案