Checking for reserved Windows filenames in .NET

Posted: (EET/GMT+2)

 

If you accept filenames from users or external tools, you may want to check for Windows reserved device names before saving them to disk.

.NET provides methods like Path.GetInvalidFileNameChars(), but these only cover invalid characters. They do not include reserved names such as nul or con.

Common reserved device names in Windows include:

  • CON
  • PRN
  • AUX
  • NUL
  • COM1COM9
  • LPT1LPT9

These names are reserved even when an extension is present, such as nul.txt or con.log.

A simple way to detect them is to maintain a small list and compare against the base filename. Here's some C# code for this:

using System;
using System.Collections.Generic;
using System.IO;

static class FilenameValidator
{
    private static readonly HashSet<string> ReservedNames =
        new HashSet<string>(StringComparer.OrdinalIgnoreCase)
        {
            "CON", "PRN", "AUX", "NUL",
            "COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9",
            "LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"
        };

    public static bool IsReservedFileName(string fileName)
    {
        string name = Path.GetFileNameWithoutExtension(fileName);
        return ReservedNames.Contains(name);
    }
}

This check can be used before creating files, uploading content, or generating paths in automation scripts.