Select Page

A file-name text box needs a clear contract before it needs a regular expression. This tutorial builds SanitizeFileName(string): replace each character returned by Path.GetInvalidFileNameChars() with an underscore, and return an underscore for empty input. The method only transforms a string; it never opens, creates, or checks a file.

The API returns a character array. Its contents depend on the platform: the Path remarks describe platform-dependent behavior. This is a filter for the current runtime’s set, not a promise that a resulting name will work on every operating system or file system.

Define what the filter changes

The replacement policy preserves the length of every nonempty input, including its extension, spaces, and repeated invalid characters. It does not trim whitespace or collapse multiple underscores. Empty input becomes _. A null argument is rejected by the guard at the beginning of the method.

The ten test inputs are report:2026.txt, a/b, con, two spaces followed by spaced and two more spaces, tab\tname, \0null, the empty string, plain.txt, what?.txt, and ... In the C# literals below, \t and \0 represent an actual tab and NUL.

Run the complete .NET 10 console example

Create a console project with the .NET 10 SDK:

dotnet new console --framework net10.0 --name FileNameFilter
cd FileNameFilter

Replace the entire contents of Program.cs with this program. If you want a refresher on the method structure, see C# Station’s lesson on methods.

using System;
using System.IO;
using System.Text;

class Program
{
    static string SanitizeFileName(string input)
    {
        ArgumentNullException.ThrowIfNull(input);
        char[] invalid = Path.GetInvalidFileNameChars();
        var result = new StringBuilder(input.Length);
        foreach (char c in input)
            result.Append(Array.IndexOf(invalid, c) >= 0 ? '_' : c);
        return result.Length == 0 ? "_" : result.ToString();
    }

    static string Show(string value)
    {
        var text = new StringBuilder("\"");
        foreach (char c in value)
        {
            if (char.IsControl(c))
                text.Append($"\\u{(int)c:X4}");
            else if (c == '\\' || c == '"')
                text.Append('\\').Append(c);
            else
                text.Append(c);
        }
        return text.Append('"').ToString();
    }

    static void Main()
    {
        string[] inputs =
        {
            "report:2026.txt", "a/b", "con", "  spaced  ",
            "tab\tname", "\0null", "", "plain.txt", "what?.txt", ".."
        };
        char[] invalid = Path.GetInvalidFileNameChars();
        Array.Sort(invalid);
        Console.WriteLine($"Invalid character count: {invalid.Length}");
        Console.WriteLine("Code points: " + string.Join(" ",
            Array.ConvertAll(invalid, c => $"U+{(int)c:X4}")));
        Console.WriteLine("Original → sanitized (control characters escaped)");
        int checks = 0;
        foreach (string input in inputs)
        {
            string output = SanitizeFileName(input);
            if (output.Length == 0)
                throw new InvalidOperationException("Empty output.");
            checks++;
            if (output.IndexOfAny(invalid) >= 0)
                throw new InvalidOperationException("Invalid character remains.");
            checks++;
            Console.WriteLine($"{Show(input)} → {Show(output)}");
        }
        Console.WriteLine($"PASS: {inputs.Length} inputs, {checks} assertions");
    }
}

Run it with:

dotnet run

SanitizeFileName obtains the invalid-character array, checks each input character for membership, and appends either an underscore or the original character. The final return supplies the nonempty fallback. The Show helper is only for the table: it puts quotes around strings and escapes control characters so tabs and NUL do not disappear into the terminal layout.

Read the observed Linux result

The complete program was compiled and run in an offline Linux container targeting net10.0. Compilation reported zero warnings and errors; stdout matched this exact transcript:

Invalid character count: 2
Code points: U+0000 U+002F
Original → sanitized (control characters escaped)
"report:2026.txt" → "report:2026.txt"
"a/b" → "a_b"
"con" → "con"
"  spaced  " → "  spaced  "
"tab\u0009name" → "tab\u0009name"
"\u0000null" → "_null"
"" → "_"
"plain.txt" → "plain.txt"
"what?.txt" → "what?.txt"
".." → ".."
PASS: 10 inputs, 20 assertions

This runtime returned two invalid characters: NUL and forward slash. Consequently, the colon, question mark, and tab passed through unchanged. The displayed \u0009 is the table helper’s representation of the retained tab, not six characters inserted by the sanitizer. The slash became an underscore, the NUL became an underscore, and the empty string used the fallback.

Run the same program on your target platform to inspect its set. Do not hard-code this Linux transcript as the expected Windows result. The two assertions inside the loop deliberately avoid an OS-specific list: every output must be nonempty, and no output may contain any character in the current API result. A failure throws instead of printing the final PASS line. Passing those assertions checks this narrow contract; it does not check every rule a filesystem may impose.

Choose additional rules before saving anything

Microsoft’s GetInvalidFileNameChars remarks warn that the array may omit characters prohibited by a particular file system. Filtering it cannot establish universal validity.

The unchanged con row makes another limitation visible. Windows naming conventions reserve device names such as CON, including names with extensions, and advise against trailing spaces or periods. A per-character filter does not implement those rules. This example intentionally leaves spaces and .. intact; it is unsuitable as a complete path-input validator.

Replacement can also merge distinct inputs: on the tested runtime, both a/b and a_b become a_b. Decide separately whether to reject such input, request another name, or assign an application-owned identifier. Nonempty does not mean unique.

When names are destined for another operating system, define and test that destination’s rules rather than relying solely on the machine running this filter. Keep directory selection and file creation separate from text cleanup. For the next string-only operation, see Path.Combine versus Path.Join; composing a path is a different contract from choosing a usable file name.

Share This