csharp / intermediate
Snippet
Sanitizing Input to Prevent Path Traversal
To prevent security vulnerabilities like path traversal, always resolve the full path and verify that it still resides within the intended base directory. Users often try to escape directories using '../' sequences.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
string baseDirectory = Path.GetFullPath("C:\\App\\Data");string userInput = "../../secrets.txt";string fullPath = Path.GetFullPath(Path.Combine(baseDirectory, userInput));if (!fullPath.StartsWith(baseDirectory, StringComparison.OrdinalIgnoreCase)){throw new SecurityException("Access denied: Path traversal detected.");}
Breakdown
1
Path.GetFullPath(...)
Resolves all relative segments and '..' to find the actual absolute path on disk.
2
fullPath.StartsWith(baseDirectory, ...)
Validates that the resulting path is a child of the secure base directory.