C#
file-path
strings
programming
code safety

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.

Browse interview questions

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.

csharp
1using System;
2using System.IO;
3using System.Linq;
4
5public static class FileNameSanitizer
6{
7    public static string MakeSafeFileName(string input)
8    {
9        if (string.IsNullOrWhiteSpace(input))
10            return "untitled";
11
12        var invalid = Path.GetInvalidFileNameChars();
13        var cleaned = new string(input
14            .Select(ch => invalid.Contains(ch) ? '_' : ch)
15            .ToArray())
16            .Trim();
17
18        cleaned = cleaned.TrimEnd('.', ' ');
19
20        return string.IsNullOrEmpty(cleaned) ? "untitled" : cleaned;
21    }
22}
csharp
Console.WriteLine(FileNameSanitizer.MakeSafeFileName("report: Q1/2026?.txt"));
text
report_ Q1_2026_.txt

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.

csharp
1using System;
2using System.Collections.Generic;
3
4public static class WindowsFileNameRules
5{
6    private static readonly HashSet<string> Reserved = new(StringComparer.OrdinalIgnoreCase)
7    {
8        "CON", "PRN", "AUX", "NUL",
9        "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
10        "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
11    };
12
13    public static string AvoidReservedName(string fileName)
14    {
15        return Reserved.Contains(fileName) ? "_" + fileName : fileName;
16    }
17}

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.

csharp
1using System;
2using System.IO;
3
4var uploadsDirectory = @"C:\AppData\Uploads";
5var safeName = FileNameSanitizer.MakeSafeFileName("invoice:03/2026.pdf");
6safeName = WindowsFileNameRules.AvoidReservedName(safeName);
7
8var fullPath = Path.Combine(uploadsDirectory, safeName);
9Console.WriteLine(fullPath);

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.txt and 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
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track 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.

Browse interview questions

All Rights Reserved.