Is there a way of making strings file-path safe in c?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Making a string file-path safe in C# usually means turning uncontrolled input into a valid file name or path segment. The important detail is that there is no single universal "safe" transformation, because Windows, Linux, and macOS do not reject exactly the same characters or reserved names.
Decide Whether You Need a File Name or a Full Path
Many implementations fail because they treat a whole path like a single file name. Those are different problems.
- A file name sanitizer should remove invalid characters from one segment such as
report:2026.txt. - A path builder should combine trusted segments with
Path.Combine.
If user input is supposed to become only the file name, sanitize that piece and keep the directory separate. That avoids accidentally allowing path traversal such as ..\..\secret.txt.
Replacing Invalid File Name Characters
For file names, the standard starting point is Path.GetInvalidFileNameChars(). Build a small sanitizer that replaces invalid characters with a safe separator.
This handles invalid characters, empty input, and the Windows rule that file names cannot end with a space or period.
Guard Against Reserved Windows Names
Character replacement is not enough on Windows. Names such as CON, PRN, AUX, and NUL are reserved even when they contain no invalid characters. Add an extra check if the application writes to Windows file systems.
In practice, combine this with the character sanitizer and run the reserved-name check after trimming.
Building the Final Path Safely
Once the file name is clean, combine it with a trusted base directory. Do not let user input control directory separators or absolute paths.
This is the reliable pattern: trusted base path plus sanitized file-name segment. If you need uniqueness, append a timestamp, database ID, or GUID instead of assuming the sanitized name will be unique.
What "Safe" Really Means
A safe file-path string usually means four separate guarantees:
- It does not contain invalid file-name characters.
- It does not resolve to a reserved system name.
- It cannot escape the intended directory.
- It is predictable enough for your application to read back later.
No single framework call handles all four. You need a small policy that matches your operating systems and naming rules.
Common Pitfalls
- Sanitizing a full path with file-name rules. That destroys valid separators and mixes two different concerns.
- Forgetting reserved names on Windows.
CON.txtand similar cases still break even after invalid-character replacement. - Allowing user input to contain directory traversal segments. Keep the directory fixed and sanitize only the file name.
- Assuming
GetInvalidPathChars()solves everything. It is not a complete security policy and is often the wrong tool for user-provided file names. - Ignoring collisions after sanitization. Different inputs can produce the same cleaned file name, so add a uniqueness strategy when needed.
Summary
- In C#, sanitize file names with
Path.GetInvalidFileNameChars(), not by hard-coding a partial list. - Treat file names and full paths as separate problems.
- Add Windows reserved-name checks if the application writes on Windows.
- Combine sanitized names with a trusted directory using
Path.Combine. - Path safety is a policy decision, not a single built-in method call.
Related reading
- Is there a way of setting culture for a whole application? All current threads and new threads?
- Is there a way to call a stored procedure with Dapper?
- Is there a way to combine LINQ and async
- Is there a way to consume a Kafka Ksql Push query from .NET
- Is there a way to force a C class to implement certain static functions?
- Is there a way to prevent Visual Studio from printing Thread exited statements into the Output Window?
- Is there a way to return Anonymous Type from method?
- Is there a way to see git diff from origin/master using Visual Studio Code?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.