【问题标题】:Why do I get an IOException when I try to consume an image file that was added to the project as a link?当我尝试使用作为链接添加到项目中的图像文件时,为什么会出现 IOException?
【发布时间】:2009-09-16 04:05:33
【问题描述】:

我在 WPF 中有一个 IValueConverter,它将相对文件路径转换为 ​​BitmapImage

守则:

public class RelativeImagePathToImage : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var relativePath = (string)value;
        if (string.IsNullOrEmpty(relativePath)) return Binding.DoNothing;
        var path = "pack://application:,,,/" + value;
        var uri = new Uri(path);
        return new BitmapImage(uri);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Binding.DoNothing;
    }
}

问题:

这个转换器工作得很好,直到我尝试将它与作为链接添加到项目中的文件一起使用(解决方案资源管理器 -> 添加现有项目 -> 添加为链接)。图像文件的BuildAction 设置为Content,文件标记为Copy Always。该文件肯定会正确复制到“bin”文件夹,但由于某种原因,转换器在到达return new BitmapImage(uri) 时会阻塞。

例外情况:

System.IO.IOException was unhandled
Message="Cannot locate resource 'images/splash.png'."
Source="PresentationFramework"

问题:

有人能解释一下吗?这是 .NET Framework 中的错误还是预期行为?是否有解决方法或者“添加为链接”不是图像内容文件的选项?

编辑:

好的,我找到了解决方法。这是我修改后的转换器类:

public class RelativeImagePathToImage : IValueConverter
{
    private static string _rootPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var relativePath = (string)value;
        if (string.IsNullOrEmpty(relativePath)) return Binding.DoNothing;
        var path = _rootPath + "/" + relativePath;
        var uri = new Uri(path);
        return new BitmapImage(uri);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Binding.DoNothing;
    }
}

显然,将packuri 与链接文件一起使用存在某种问题。但为什么呢?

【问题讨论】:

    标签: c# wpf visual-studio relative-path


    【解决方案1】:

    答案是使用pack://siteoforigin:,,,/ 而不是pack://application:,,,/

    pack://siteoforigin 适用于复制到 bin/Debug 或 bin/Release 文件夹(或其中的任何子文件夹)的任何内容文件,无论该文件是作为链接添加到项目中还是正常添加到项目中。

    path://application 仅适用于正常添加的内容文件(不作为链接)。

    【讨论】:

      【解决方案2】:

      pack:// uri 方案仅用于资源目录中的文件,如果您只是添加文件或添加文件作为链接并将其类型设置为“内容”,则只会将文件复制到您的 bin文件夹,但不会打包在应用程序资源目录中。

      所以对于作为单独文件存在于目录中的文件,你不能使用pack uri方案,你必须使用普通路径的文件uri方案。此行为与文件是否作为链接添加或复制无关,它取决于文件的导出方式。

      【讨论】:

      • 但是对于放置在文件夹中并设置为Content - Copy Always 的图像文件,该代码可以正常工作。仅当我使用链接而不是将文件存储在文件夹中时,它才停止工作。
      • +1,这足以解决我的问题:文件一个项目文件夹深 = 工作正常。两个项目文件夹深 = 异常。可笑。
      猜你喜欢
      • 2021-08-10
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 2019-04-20
      • 1970-01-01
      • 2014-08-31
      相关资源
      最近更新 更多