# System.ArgumentException: 路径中存在非法字符。

- **ID:** `dotnet/illegal-char-in-path`
- **领域:** dotnet
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

文件路径包含操作系统不允许的字符，例如冒号、星号或尖括号，通常是由于用户输入或配置格式错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| net6.0 | active | — | — |
| net7.0 | active | — | — |
| net8.0 | active | — | — |
| net9.0 | active | — | — |

## 解决方案

1. ```
   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)));'
   ```
2. ```
   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.
   ```
3. ```
   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 '\')** — The issue is not the separator but illegal characters like ':', '?', '*' which are invalid on Windows regardless of separator. (70% 失败率)
- **Using Path.GetInvalidPathChars() to remove characters but only checking for a subset** — GetInvalidPathChars() does not include all illegal characters (e.g., ':' is valid for drive letters but not in middle of path), leading to incomplete validation. (80% 失败率)
- **Truncating the path to a fixed length** — Truncation does not remove illegal characters; it may cut off valid parts and still leave invalid chars. (90% 失败率)
