C# Reserved FilenamesDevelop a class that checks for reserved file names. Prevent errors from incorrect file names.
dot net perls
Reserved file names cannot be used. We can detect these names in strings in a C# program. This ensures we do not generate an invalid file name.
Some examples. Some reserved file names are CON.txt, PRN.doc and nul.exe. If we need to generate file names, we can test to ensure we do not choose a reserve done.
Reserved list. Here is a list of file names that cannot be used in Windows. On other operating systems like Linux and macOS these file names are not reserved.
Reserved file names 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
aux.txt Con.bin NUL.png com2.png lpt8.aspx
Example code. This issue can occur when a Windows server tries to serve a file such as PRN.aspx, which is dynamically generated. This code can detect such invalid file names.
C# program that tests for reserved names
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); } }
Performance note. This code could be sped up with a static Dictionary. But the performance difference is not important in many cases.
Static Dictionary
Info The C# Array.IndexOf method could also be used to replace the foreach-loop.
Array.IndexOf, LastIndexOf
A summary. We saw a useful method—it can detect the invalid file names that Windows reserves. This includes all the Windows server environments, such as IIS.
© 2007-2021 sam allen. see site info on the changelog