打包uri验证

Ber*_*ryl 5 c# uri

验证可以找到包uri的最简单方法是什么?

例如,给定

pack://application:,,,Rhino.Mocks;3.5.0.1337;0b3305902db7183f;component/SomeImage.png
Run Code Online (Sandbox Code Playgroud)

我该如何检查图像是否真的存在?

干杯,
Berryl

Ber*_*ryl 5

我找不到一个简单的答案,所以我结束了自己的代码来完成关于图像资源的三件事:
(1)有一个包uri(数据绑定)的字符串表示
(2)验证图像位于我认为它所在的位置(单元测试)
(3)验证包uri是否可用于设置图像(单元测试)

这个并不简单的部分原因是因为打包uri一开始有点混乱,并且有几种风格.此代码用于包uri,表示包含在VS程序集中的图像(本地或带有'resource'构建操作的引用程序集.这篇msdn文章阐明了在此上下文中的含义.您还需要了解更多关于组件和构建比最初似乎是一个好时机.

希望这会让其他人更容易.干杯,
Berryl

    /// <summary> (1) Creates a 'Resource' pack URI .</summary>
    public static Uri CreatePackUri(Assembly assembly, string path, PackType packType)
    {
        Check.RequireNotNull(assembly);
        Check.RequireStringValue(path, "path");

        const string startString = "pack://application:,,,/{0};component/{1}";
        string packString;
        switch (packType)
        {
            case PackType.ReferencedAssemblySimpleName:
                packString = string.Format(startString, assembly.GetName().Name, path);
                break;
            case PackType.ReferencedAssemblyAllAvailableParts:
                // exercise for the reader
                break;
            default:
                throw new ArgumentOutOfRangeException("packType");
        }
        return new Uri(packString);
    }

    /// <summary>(2) Verify the resource is located where I think it is.</summary>
    public static bool ResourceExists(Assembly assembly, string resourcePath)
    {
        return GetResourcePaths(assembly).Contains(resourcePath.ToLowerInvariant());
    }

    public static IEnumerable<object> GetResourcePaths(Assembly assembly, CultureInfo culture)
    {
        var resourceName = assembly.GetName().Name + ".g";
        var resourceManager = new ResourceManager(resourceName, assembly);

        try
        {
            var resourceSet = resourceManager.GetResourceSet(culture, true, true);

            foreach (DictionaryEntry resource in resourceSet)
            {
                yield return resource.Key;
            }
        }
        finally
        {
            resourceManager.ReleaseAllResources();
        }
    }

    /// <summary>(3) Verify the uri can construct an image.</summary>
    public static bool CanCreateImageFrom(Uri uri)
    {
        try
        {
            var bm = new BitmapImage(uri);
            return bm.UriSource == uri;
        }
        catch (Exception e)
        {
            Debug.WriteLine(e);
            return false;
        }
    }
Run Code Online (Sandbox Code Playgroud)