2011-03-30 58 views
2

在WPF中,下面的代码返回给定位置的所有字体的列表:WPF Fonts.GetFontFamilies()缓存字体列表,如何清除缓存?

foreach (var fontFamily in Fonts.GetFontFamilies(@"C:\Dummy\Fonts\")) 
{ 
    System.Diagnostics.Debug.WriteLine(fontFamily.Source); 
} 

的问题是,如果你更改该文件夹(添加或删除字体)的内容和运行此代码再次,它返回相同的列表(因为它是缓存内部某处)。

这个缓存不会被清除,直到你的退出该应用程序!

有什么办法可以防止这种行为,并且总是让WPF在那个时候查看那个文件夹的字体吗?

注:结果是无论“的Windows Presentation Foundation字体缓存3.0.0.0”服务状态启动或停止的一样。显然,这种特定类型的缓存并未被服务处理。

+0

当您在Debug和Release配置中运行应用程序时,会发生这种情况吗?我有一个类似的问题,只发生在调试模式下。 – 2011-03-30 15:09:43

+0

是的,它是一样的,不管我在Release/Debug/VS/Standalone内运行应用程序。总是缓存在那里。 – 2011-03-30 15:14:33

回答

2

我相信您可能需要disable the font cache service,因为它可能会在需要时自动启动。

编辑:

您可能需要获得的FontFamily对象列表自己就像这样:

private static FontFamily CreateFontFamily(string path) { 
    Uri uri; 
    if (!Uri.TryCreate(path, UriKind.Absolute, out uri)) 
     throw new ArgumentException("Must provide a valid location", "path"); 

    return new FontFamily(uri, string.Empty); 
} 

public static IEnumerable<FontFamily> GetNonCachedFontFamilies(string location) { 
    if (string.IsNullOrEmpty("location")) 
     throw new ArgumentException("Must provide a location", "location"); 

    DirectoryInfo directoryInfo = new DirectoryInfo(location); 
    if (directoryInfo.Exists) { 
     FileInfo[] fileInfos = directoryInfo.GetFiles("*.?tf"); 
     foreach (FileInfo fileInfo in fileInfos) 
      yield return CreateFontFamily(fileInfo.FullName); 
    } 
    else { 
     FileInfo fileInfo = new FileInfo(location); 
     if (fileInfo.Exists) 
      yield return CreateFontFamily(location); 
    } 
} 

可能有一些问题,与家人的名字,但上面的应该让你大部分的相关信息。

+1

恐怕即使有残疾人服务,结果也是一样的。 显然,该服务只负责“字体文件夹”和“Fonts.GetFontFamilies()”使用另一个缓存系统。 – 2011-03-31 09:17:07

+0

@shayan - 我已经更新了我的答案,以包含手动获取相关字体系列的示例,这可能适用于您的情况,也可能不适用。 – CodeNaked 2011-04-03 00:07:51

+0

这是一个很好的解决方法! – 2011-04-04 13:46:01