C# GDI+发生一般性错误 A generic error occurred in GDI+
生产上在使用Image.Save方法的时候,时不时的出现以下错误,让人头大
A generic error occurred in GDI+
因为是时不时出现的,不是100%的出现,所以就问题就比较难搞了,依次做了以下尝试:
1、检查文件夹存不存在
2、检查图像能否正常显示
3、检查是否有写入权限
均正常
按照C# GDI+发生一般性错误(A generic error occurred in GDI+)) - guangfengli - 博客园 (cnblogs.com)这篇文章的方法,尝试获取错误代码
var code = Marshal.GetLastWin32Error(); throw new Exception(exp.Message + ":" + code.ToString(), exp);
结果错误代码是 0
Tutorial - Debug system error codes - Win32 apps | Microsoft Docs
按照微软错误代码表格:
ERROR_SUCCESS 0 (0x0) The operation completed successfully.
最后,仔细观察了要保存的文件名后发现文件名里有不允许出现的特殊字符
附上除去文件名特殊字符的方法:
protected string ReplaceFileSpecialChar(string name, string replaceWith = " ") { if (IsFileNameValid(name)) return name; var result = ""; List<string> errorStr = new List<string>() { "/", "\\", ":", ",", "*", "?", "\"", "<", ">", "|" }; for (int i = 0; i < name.Length; i++) { var ch = name[i].ToString(); if (errorStr.Contains(ch)) result += replaceWith; else result += ch; } return result; } private bool IsFileNameValid(string name) { bool isFilename = true; string[] errorStr = new string[] { "/", "\\", ":", ",", "*", "?", "\"", "<", ">", "|" }; if (string.IsNullOrEmpty(name)) { isFilename = false; } else { for (int i = 0; i < errorStr.Length; i++) { if (name.Contains(errorStr[i])) { isFilename = false; break; } } } return isFilename; }