dotnet
config_error
ai_generated
true
System.ArgumentException: 路径中存在非法字符。
System.ArgumentException: Illegal characters in path.
ID: dotnet/illegal-char-in-path
85%修复率
85%置信度
1证据数
2023-03-20首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| net6.0 | active | — | — | — |
| net7.0 | active | — | — | — |
| net8.0 | active | — | — | — |
| net9.0 | active | — | — | — |
根因分析
文件路径包含操作系统不允许的字符,例如冒号、星号或尖括号,通常是由于用户输入或配置格式错误。
English
A file path contains characters not allowed by the operating system, such as colons, asterisks, or angle brackets, often due to user input or malformed configuration.
官方文档
https://learn.microsoft.com/en-us/dotnet/api/system.io.pathtoo longexception?view=net-8.0解决方案
-
Sanitize the path using Path.GetInvalidFileNameChars() and Path.GetInvalidPathChars() to replace or remove illegal characters. Example: 'string safePath = string.Concat(path.Where(c => !Path.GetInvalidPathChars().Contains(c) && !Path.GetInvalidFileNameChars().Contains(c)));'
-
Use Path.Combine() to build paths safely instead of string concatenation. For user input, validate with a regex like '^[a-zA-Z0-9_\\-./\\s]+$' and reject invalid input early.
-
Wrap file path operations in try-catch for ArgumentException and log the path for debugging. Then, implement a fallback like using a GUID-based file name: 'string safeFileName = Guid.NewGuid().ToString() + Path.GetExtension(originalPath);'
无效尝试
常见但无效的做法:
-
Hardcoding the path with a different separator (e.g., using '/' instead of '\')
70% 失败
The issue is not the separator but illegal characters like ':', '?', '*' which are invalid on Windows regardless of separator.
-
Using Path.GetInvalidPathChars() to remove characters but only checking for a subset
80% 失败
GetInvalidPathChars() does not include all illegal characters (e.g., ':' is valid for drive letters but not in middle of path), leading to incomplete validation.
-
Truncating the path to a fixed length
90% 失败
Truncation does not remove illegal characters; it may cut off valid parts and still leave invalid chars.