Reserved FilenamesDevelop a class that checks for reserved file names. Prevent errors from incorrect file names.
This page was last reviewed on Jun 2, 2021.
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.
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.
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.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 2, 2021 (rewrite).
© 2007-2023 Sam Allen.