无法在Bitmap路径参数中引用JPG:路径含非法字符异常求助
这个问题我日常开发中碰到过好多次,从你给出的异常信息来看,核心原因就是传入Bitmap构造函数的文件路径里包含了Windows系统不允许的非法字符,或者路径本身的格式有问题。咱们一步步来解决:
第一步:先排查路径本身的问题
- 先确认你传入的路径里有没有这些非法字符:
<,>,:,",/,\,|,?,*,Windows文件路径里绝对不能出现这些字符。 - 如果用的是相对路径,一定要注意程序运行时的工作目录是不是你预期的项目文件夹。可以在代码里加一行调试代码,先看看当前工作目录:
很多时候相对路径出错,都是因为工作目录和你想的不一样。Console.WriteLine(Directory.GetCurrentDirectory());
第二步:用正确的方式拼接路径
手动拼接路径很容易出错,推荐用.NET自带的Path.Combine()方法来生成合法路径,它会自动处理不同系统的路径分隔符,避免手动写斜杠出错。比如你的图片放在项目根目录下,就这么写:
// 获取程序运行的根目录 string rootPath = AppDomain.CurrentDomain.BaseDirectory; // 拼接图片路径 string imagePath = Path.Combine(rootPath, "your-image-file.jpg"); // 实例化Bitmap Bitmap imgBitmap = new Bitmap(imagePath);
第三步:检查传入方法的参数
看你报错的代码是在differance方法里(这里应该是拼写错误,建议改成difference),你可以在调用这个方法前,先把传入的img1和img2路径打印出来,看看是不是不小心传入了奇怪的内容,比如多了引号、或者路径被截断了:
Console.WriteLine($"img1路径:{img1}"); Console.WriteLine($"img2路径:{img2}"); var result = differance(img1, img2);
你提供的异常信息:
Unhandled Exception: System.ArgumentException: Illegal characters in path.
at System.IO.Path.LegacyNormalizePath(String path, Boolean fullCheck, Int32 maxPathLength, Boolean expandShortPaths)
at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength, Boolean expandShortPaths)
at System.IO.Path.GetFullPathInternal(String path)
at System.IO.Path.GetFullPath(String path)
at System.Drawing.IntSecurity.UnsafeGetFullPath(String fileName)
at System.Drawing.IntSecurity.DemandReadFileIO(String fileName)
at System.Drawing.Bitmap..ctor(String filename)
at ConsoleImageCompare.Compare.differance(String img1, String img2) in c:\users\user\documents\visual studio 2017\Projects\ConsoleImageCompare\ConsoleImageCompare\Compare.cs:line 22
at ConsoleImageCompare.Program.Main(String[] args)
这个异常已经明确指向了路径里的非法字符,所以重点排查路径内容和生成方式就可以解决啦。
内容的提问来源于stack exchange,提问作者TSS

