6

我正在尝试从文件系统上保存的文件中加载一些 BitmapImages。我有一个键和相对文件路径的字典。不幸的是,Uri 构造函数在加载图像的方式上似乎是不确定的。

这是我的代码:

foreach(KeyValuePair<string, string> imageLocation in _imageLocations)
{
    try
    {
        BitmapImage img = new BitmapImage();
        img.BeginInit();
        img.UriSource = new Uri(@imageLocation.Value, UriKind.Relative);

        img.EndInit();
        _images.Add(imageLocation.Key, img);
    }
    catch (Exception ex)
    {
        logger.Error("Error attempting to load image", ex);

    }
}

不幸的是,有时 Uris 会作为相对文件 Uris 加载,有时它们会作为相对 Pack Uris 加载。似乎没有任何押韵或理由说明哪个会以哪种方式加载。有时我会以一种方式加载所有的 Uris,或者只加载几个,或者大多数,每次运行代码时它都会改变。

有什么想法吗?

4

2 回答 2

3

嗯,有点... MSDN 对 UriKind 有这样的说法:

绝对 URI 的特点是对资源的完整引用(例如: http: //www.contoso.com/index.html),而相对 Uri 取决于先前定义的基本 URI(例如:/index.html)

如果您跳入反射器并环顾四周,您会发现代码有很多路径可以用来解析相对 URI 应该是什么。无论如何,这并不是它的不确定性,更多的是它只是许多开发人员沮丧的主要来源。您可以做的一件事是使用“ BaseUriHelper ”类来深入了解您的 uri 是如何被解析的。

另一方面,如果您知道您的资源存储在哪里(并且您应该知道),我建议您不必担心,并使用绝对 URI 来解析您的资源。每次都有效,并且在您最不期望的时候,幕后没有愚蠢的代码会绊倒您。

于 2011-04-21T13:06:10.337 回答
1

最后,我通过获取我的应用程序的基本目录并将相对路径附加到该目录并使用绝对 URI 而不是相对路径来解决问题。

string baseDir = AppDomain.CurrentDomain.BaseDirectory;

foreach(KeyValuePair<string, string> imageLocation in _imageLocations)
{
    try
    {
        BitmapImage img = new BitmapImage();
        img.BeginInit();
        img.UriSource = new Uri("file:///" + baseDir + @imageLocation.Value, UriKind.Absolute);

        img.EndInit();
        _images.Add(imageLocation.Key, img);
    }
    catch (Exception ex)
    {
        logger.Error("Error attempting to load image", ex);

    }
}
于 2011-04-28T05:05:56.630 回答