# System.ArgumentException: Illegal characters in path.

- **ID:** `dotnet/illegal-char-in-path`
- **Domain:** dotnet
- **Category:** config_error
- **Verification:** ai_generated
- **Fix Rate:** 85%

## Root Cause

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.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| net6.0 | active | — | — |
| net7.0 | active | — | — |
| net8.0 | active | — | — |
| net9.0 | active | — | — |

## Workarounds

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)));'** (90% success)
   ```
   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.** (85% success)
   ```
   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);'** (80% success)
   ```
   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);'
   ```

## Dead Ends

- **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% fail)
- **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% fail)
- **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% fail)
