C# Reserved Filenames

String type

Reserved file names cannot be used. We can detect these names in strings in a C# program. This ensures we don't generate an invalid file name.
Some reserved file names are CON.txt,
PRN.doc
and nul.exe.

Reserved filenames in Windows operating systems

aux
con
clock$
nul
prn

com1
com2
com3
com4
com5
com6
com7
com8
com9

lpt1
lpt2
lpt3
lpt4
lpt5
lpt6
lpt7
lpt8
lpt9

Examples of reserved filenames

aux.txt
Con.bin
NUL.png
com2.png
lpt8.aspx

Example

First, this problem can occur when a Windows server tries to serve a file such as PRN.aspx, which is dynamically generated. The file will not be available. I wrote this C# static class to detect such invalid file names.

Static Class
Class that contains reserved names: C#

using System.IO;

/// <summary>
/// Contains logic for detecting reserved file names.
/// </summary>
static class ReservedFileNameTool
{
    /// <summary>
    /// Reserved file names in Windows.
    /// </summary>
    static string[] _reserved = new string[]
    {
	"con",
	"prn",
	"aux",
	"nul",
	"com1",
	"com2",
	"com3",
	"com4",
	"com5",
	"com6",
	"com7",
	"com8",
	"com9",
	"lpt1",
	"lpt2",
	"lpt3",
	"lpt4",
	"lpt5",
	"lpt6",
	"lpt7",
	"lpt8",
	"lpt9",
	"clock$"
    };

    /// <summary>
    /// Determine if the path file name is reserved.
    /// </summary>
    public static bool IsReservedFileName(string path)
    {
	string fileName = Path.GetFileNameWithoutExtension(path); // Extension doesn't matter
	fileName = fileName.ToLower(); // Case-insensitive
	foreach (string reservedName in _reserved)
	{
	    if (reservedName == fileName)
	    {
		return true;
	    }
	}
	return false;
    }

    /// <summary>
    /// Determine if the path file name is reserved.
    /// </summary>
    public static bool IsNotReservedFileName(string path)
    {
	return !IsReservedFileName(path);
    }
}
File: text page

You can save this static class in a file. We call its public static method IsReservedFileName to determine if a path has a reserved file name. In Windows, you are allowed to use the first letters in a reserved name as a file name.

But:There must be further letters.
You are not allowed to use the reserved file names.

Summary

The C# programming language

We saw a useful method. It can detect the invalid file names that Windows reserves. This includes Windows XP, Windows Vista, and all the Windows server environments, such as IIS 6.0 and IIS 7.0.

Note:This code could be sped up with a static Dictionary. But the performance difference isn't important in many cases.

Static Dictionary

C#: File: Path