【发布时间】:2015-08-11 00:54:37
【问题描述】:
我想显示与文件关联的图标。对于与普通桌面应用程序关联的文件类型,这不是问题,但仅对与(都市/现代)应用程序关联的文件类型。
如果文件类型与应用程序相关联并且我正在使用AsParallel(),我只会得到默认的未知文件类型图标。澄清一下,我没有得到null 或空图标,而是显示空纸张的默认图标。如果没有AsParallel(),我会得到正确的图标。
我尝试了其他几种方法来获取图标,例如,SHGetFileInfo() 或直接通过 dll 调用 ExtractAssociatedIcon()。行为总是一样的。
示例:如果“Adobe Acrobat”是 PDF 文件的默认应用程序,那么在这两种情况下我都会得到正确的 Adobe PDF 图标。如果 Windows 8 或 10 中的内置(现代 UI)应用“阅读器”是默认应用,则在应用 AsParallel() 时,我会看到未知文件类型图标。
MCVE
XAML:
<Window x:Class="FileIconTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<TextBox x:Name="TxtFilename" Text="x:\somefile.pdf"/>
<Button Click="Button_Click">Go</Button>
<Image x:Name="TheIcon" Stretch="None"/>
</StackPanel>
</Window>
对应代码:
private void Button_Click(object sender, RoutedEventArgs e)
{
var list = new List<string>();
list.Add(TxtFilename.Text);
var icons = list.AsParallel().Select(GetIcon); // problem with apps
// var icons = list.Select(GetIcon); // works always
TheIcon.Source = icons.First();
}
public static ImageSource GetIcon(string filename)
{
var icon = System.Drawing.Icon.ExtractAssociatedIcon(filename);
var iSource = Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
iSource.Freeze();
return iSource;
}
使用说明:仅使用两种变体中的一种。如果两者都执行,即使使用不同的变量,问题也可能无法重现。
【问题讨论】: