现象:

  打印时候程序直接崩溃。调试时出现下列异常。

异常信息:

  中文:System.ArgumentException : 路径中有非法字符。

  英文: System.ArgumentException' occurred in mscorlib.dll  Additional information: Illegal characters in path

堆栈信息:

Stack Trace:=
   at System.IO.Path.CheckInvalidPathChars(String path)
   at System.IO.Path.Combine(String path1, String path2)
   at Microsoft.Internal.GDIExporter.BuildFontList(String fontdir)
   at Microsoft.Internal.GDIExporter.CGDIDevice.CheckFont(GlyphTypeface typeface, String name)
   at Microsoft.Internal.GDIExporter.CGDIRenderTarget.CreateFontW(GlyphRun pGlyphRun, Double fontSize, Double scaleY)
   at Microsoft.Internal.GDIExporter.CGDIRenderTarget.RenderTextThroughGDI(GlyphRun pGlyphRun, Brush pBrush)
   at Microsoft.Internal.GDIExporter.CGDIRenderTarget.DrawGlyphRun(Brush pBrush, GlyphRun glyphRun)
   at Microsoft.Internal.AlphaFlattener.BrushProxyDecomposer.Microsoft.Internal..AlphaFlattener.IProxyDrawingContext.DrawGlyphs(GlyphRun glyphrun, Geometry clip, Matrix trans, BrushProxy foreground)
   at Microsoft.Internal.AlphaFlattener.PrimitiveRenderer.DrawGlyphs(GlyphRun glyphrun, Rect bounds, Matrix trans, String desp)
   at Microsoft.Internal.AlphaFlattener.Flattener.AlphaRender(Primitive primitive, List` overlapping, Int32 overlapHasTransparency, Boolean disjoint, String desp)
   at Microsoft.Internal.AlphaFlattener.Flattener.AlphaFlatten(IProxyDrawingContext dc, Boolean disjoint)
   at Microsoft.Internal.AlphaFlattener.Flattener.Convert(Primitive tree, ILegacyDevice dc, Double width, Double height, Double dpix, Double dpiy, Nullable` quality)
   at Microsoft.Internal.AlphaFlattener.MetroDevice0.FlushPage(ILegacyDevice sink, Double width, Double height, Nullable` outputQuality)
   at Microsoft.Internal.AlphaFlattener.MetroToGdiConverter.FlushPage()
   at System.Windows.Xps.Serialization.NgcSerializationManager.EndPage()
   at System.Windows.Xps.Serialization.NgcFixedPageSerializer.SerializeObject(Object serializedObject)
   at System.Windows.Xps.Serialization.NgcDocumentPageSerializer.SerializeObject(Object serializedObject)
   at System.Windows.Xps.Serialization.NgcDocumentPaginatorSerializer.SerializeObject(Object serializedObject)
   at System.Windows.Xps.Serialization.NgcSerializationManager.SaveAsXaml(Object serializedObject)
   at System.Windows.Xps.XpsDocumentWriter.SaveAsXaml(Object serializedObject, Boolean isSync)
   at System.Windows.Xps.XpsDocumentWriter.Write(DocumentPaginator documentPaginator)
   at System.Windows.Controls.PrintDialog.PrintDocument(DocumentPaginator documentPaginator, String description)

原因:

  在注册表 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts 中存的是字体名称及其文件位置的列表。但这些文件位置中有非法字符中有非法字符。在执行Path.Combine方法时,出现异常。

解决方案:

  重新处理注册表。

代码:

    public class FontsClearup
{
/// <summary>
/// 获取系统文件位置
/// </summary>
[MethodImpl(MethodImplOptions.ForwardRef), SecurityCritical, SuppressUnmanagedCodeSecurity, DllImport("shell32.dll", CharSet = CharSet.Unicode)]
internal static extern int SHGetSpecialFolderPathW(IntPtr hwndOwner, StringBuilder lpszPath, int nFolder, int fCreate); /// <summary>
/// 获取字体文件夹
/// </summary>
/// <returns></returns>
private static string GetFontDir()
{
var lpszPath = new StringBuilder();
return SHGetSpecialFolderPathW(IntPtr.Zero, lpszPath, , ) != ? lpszPath.ToString().ToUpperInvariant() : null;
} public const string FontsRegistryPath =
@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Fonts";
public const string FontsLocalMachineRegistryPath =
@"Software\Microsoft\Windows NT\CurrentVersion\Fonts"; /// <summary>
/// 获取所有字体信息
/// </summary>
/// <returns></returns>
public static IEnumerable<FontInfo> ScanAllRegistryFonts()
{
var fontNames = new List<FontInfo>();
new RegistryPermission(RegistryPermissionAccess.Read, FontsRegistryPath).Assert();
try
{
var fontDirPath = GetFontDir();
using (var key = Registry.LocalMachine.OpenSubKey(FontsLocalMachineRegistryPath))
{
if (key == null)
{
return Enumerable.Empty<FontInfo>();
}
var valueNames = key.GetValueNames();
foreach (var valueName in valueNames)
{
var fontName = key.GetValue(valueName).ToString();
var fontInfo = new FontInfo
{
Name = valueName,
RegistryKeyPath = key.ToString(),
Value = fontName
};
try
{
var systemFontUri = new Uri(fontName, UriKind.RelativeOrAbsolute);
if (!systemFontUri.IsAbsoluteUri)
{
new Uri(Path.Combine(fontDirPath, fontName));
}
}
catch
{
fontInfo.IsCorrupt = true;
}
fontNames.Add(fontInfo);
}
key.Close();
key.Flush();
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
finally
{
CodeAccessPermission.RevertAssert();
}
return fontNames;
} /// <summary>
/// 获取所有异常字体信息
/// </summary>
/// <returns></returns>
public static IEnumerable<FontInfo> GetAllCorruptFonts()
{
var fonts = ScanAllRegistryFonts();
return fonts.Where(f => f.IsCorrupt);
} /// <summary>
/// 整理字体信息
/// </summary>
/// <param name="p_corruptFonts"></param>
public static void FixRegistryFonts(IEnumerable<FontInfo> p_corruptFonts = null)
{
IEnumerable<FontInfo> corruptFonts = p_corruptFonts;
if (corruptFonts == null)
{
corruptFonts = GetAllCorruptFonts();
} new RegistryPermission(RegistryPermissionAccess.Write, FontsRegistryPath).Assert();
try
{
using (var key = Registry.LocalMachine.OpenSubKey(FontsLocalMachineRegistryPath, true))
{
if (key == null) return;
foreach (var corruptFont in corruptFonts)
{
if (!corruptFont.IsCorrupt) continue;
var fixedFontName = RemoveInvalidCharsFormFontName(corruptFont.Value);
key.SetValue(corruptFont.Name, fixedFontName, RegistryValueKind.String);
}
key.Close();
key.Flush();
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
finally
{
CodeAccessPermission.RevertAssert();
ScanAllRegistryFonts();
}
} private static string RemoveInvalidCharsFormFontName(string fontName)
{
var invalidChars = Path.GetInvalidPathChars();
var fontCharList = fontName.ToCharArray().ToList();
fontCharList.RemoveAll(c => invalidChars.Contains(c));
return new string(fontCharList.ToArray());
}
} public class FontInfo
{
public string RegistryKeyPath { get; set; }
public bool IsCorrupt { get; set; }
public string Name { get; set; }
public string Value { get; set; } }

执行:FontsClearup.FixRegistryFonts();

其实方法的用法见注释。

参考:http://www.dnsingh.com/MyBlog/?tag=/GDIExporter.BuildFontList

WPF 打印崩溃问题( 异常:Illegal characters in path/路径中有非法字符)的更多相关文章

  1. 【已解决】unity4.2.0f4 导出Android工程报错:Error building Player: ArgumentException: Illegal characters in path. [unity导出android工程 报错,路径含有非法字符]

    使用unity3D开发的一个客户端,需要导出为Android工程,然后接入一些第三方android SDK. unity版本 操作系统为: OS 名称: Microsoft Windows 7 旗舰版 ...

  2. VS2017 v15.8.0 Task ExpandPriContent failed. Illegal characters in path

    昨天更新了VS到最新版本v15.8.0,但是编译UWP出现了操蛋的bug. 谷歌一下,vs社区已经有答案了. 打开.csproj文件,在节点 <PropertyGroup> 里面,加上一行 ...

  3. URLDecoder异常Illegal hex characters in escape (%)

    URLDecoder对参数进行解码时候,代码如: URLDecoder.decode(param,"utf-8"); 有时候会出现类似如下的错误: URLDecoder异常Ille ...

  4. 引擎崩溃、异常、警告、BUG与提示总结及解决方法

    http://www.58player.com/blog-635-128.html [Unity3D]引擎崩溃.异常.警告.BUG与提示总结及解决方法   此贴会持续更新,都是项目中常会遇到的问题,总 ...

  5. WPF打印票据

    最近工作的内容是有关于WPF的,整体开发没有什么难度,主要是在打印上因为没有任何经验,犯了一些难,不过还好,解决起来也不是很费劲. WPF打印票据或者是打印普通纸张区别不大,只是说打印票据要把需要打的 ...

  6. WPF 打印实例

    原文:WPF 打印实例      在WPF 中可以通过PrintDialog 类方便的实现应用程序打印功能,本文将使用一个简单实例进行演示.首先在VS中编辑一个图形(如下图所示).      将需要打 ...

  7. 【Bug】解决 SpringBoot Artifact contains illegal characters 错误

    解决 SpringBoot  Artifact contains illegal characters错误 错误原因:Artifact包含非法字符(大写字母) 解决方法:将Artifact名称改成小写 ...

  8. IDEA中新建SpringBoot项目时提示:Artifact contains illegal characters

    场景 一步一步教你在IEDA中快速搭建SpringBoot项目: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/87688277 ...

  9. Linux curl遇到错误curl: (3) Illegal characters found in URL

    服务器上执行一个脚本,在linux新建的sh,把本地编辑器的内容粘贴到文件里. 结果执行的时候报错了. 问题就是 curl:(3)Illegal characters found in URL 看着一 ...

随机推荐

  1. 第八章 高级搜索树 (a3)伸展树:算法实现

  2. Food(最大流)

    Food http://acm.hdu.edu.cn/showproblem.php?pid=4292 Time Limit: 2000/1000 MS (Java/Others)    Memory ...

  3. 基于Python Shell获取hostname和fqdn释疑

    一直以来被Linux的hostname和fqdn(Fully Qualified Domain Name)困惑了好久,今天专门抽时间把它们的使用细节弄清了. 一.设置hostname/fqdn 在Li ...

  4. .NET资源文件实现多语言切换

    1.创建对应的资源文件 lang.en.resx  英文 lang.resx   中文,默认 lang.zh-tw.resx  繁体 首先说明,这三个文件前面部分名称需要一样,只是 点 后面的语言代号 ...

  5. jmeter 常见问题汇总

    文件读取中文乱码: 读取CSV文件,出现中文乱码,纠正方式如下: txt文件乱码 在用到该变量的请求上加上UTF-8 post请求 返回“ Content type 'application/x-ww ...

  6. dir/

    dos窗口输入dir命令是显示磁盘目录命令: addslashes()使用反斜线转义字符串: exec($command,$output,$return)执行一个外部程序 $command:要执行的命 ...

  7. Java NIO系列教程(十一) Java NIO 与 IO

    Java NIO系列教程(十一) Java NIO与IO 当学习了 Java NIO 和 IO 的 API 后,一个问题马上涌入脑海: 我应该何时使用 IO,何时使用 NIO 呢?在本文中,我会尽量清 ...

  8. Android窗口背景的优化

    视图有背景,每个窗口也是有背景的.每一Activity是一个窗口,每一个Activity都有不同得背景.界面的绘画顺序如下:窗口——跟视图 ——子视图.当我们的跟视图已经覆盖了整个窗口的时候 ,程序还 ...

  9. 2018.10.19 NOIP训练 变化的序列(线性dp)

    传送门 f[i][j]f[i][j]f[i][j]表示后iii个对答案贡献有jjj个a的方案数. 可以发现最后a,ba,ba,b的总个数一定是n∗(n−1)/2n*(n-1)/2n∗(n−1)/2 因 ...

  10. 2018.08.29 NOIP模拟 movie(状压dp/随机化贪心)

    [描述] 小石头喜欢看电影,选择有 N 部电影可供选择,每一部电影会在一天的不同时段播 放.他希望连续看 L 分钟的电影.因为电影院是他家开的,所以他可以在一部电影播放过程中任何时间进入或退出,当然他 ...