Skip to content

Instantly share code, notes, and snippets.

@andylshort
Created October 29, 2018 16:48
Show Gist options
  • Save andylshort/31eb90a732b7f031e5098a551d9e2f4f to your computer and use it in GitHub Desktop.
Save andylshort/31eb90a732b7f031e5098a551d9e2f4f to your computer and use it in GitHub Desktop.
Windows has reserved filenames, this prevents clashes and problems
using System.IO;
/// <summary>
/// Contains logic for detecting reserved file names in Windows.
/// </summary>
static class ReservedFileNameTool
{
/// <summary>
/// Reserved file names in Windows.
/// </summary>
private static readonly 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 FilePath)
{
string FileName = Path.GetFileNameWithoutExtension(FilePath); // 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);
}
public static string FixFilename(string path)
{
if (IsReservedFileName(path))
{
string parent = Path.GetDirectoryName(path);
string ext = Path.GetExtension(path);
string fn = Path.GetFileNameWithoutExtension(path);
return Path.Combine(parent, $"{fn}-{ext}");
}
else
{
return path;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment