Skip to content

Instantly share code, notes, and snippets.

@5cover
Last active November 19, 2022 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 5cover/ee25f747e6af3cc96d79c27a530b4430 to your computer and use it in GitHub Desktop.
Save 5cover/ee25f747e6af3cc96d79c27a530b4430 to your computer and use it in GitHub Desktop.
Create a valid NTFS Windows filename out of a string
/// <summary>Creates a valid Windows filename from a string.</summary>
/// <param name="filename">The filename candidate.</param>
/// <param name="replaceInvalidCharsWith">What to replace invalid filename chars in <paramref name="filename"/> with.</param>
/// <returns>
/// A new <see cref="string"/>, equivalent to <paramref name="filename"/>, but modified to be a valid Windows filename if it
/// <paramref name="filename"/> wasn't already.
/// </returns>
/// <exception cref="ArgumentException"/>
/// <remarks>The length of the filename is not checked, and the casing is not modified.</remarks>
public static string ToFilename(this string filename, string replaceInvalidCharsWith = "_")
=> string.IsNullOrWhiteSpace(filename)
? throw new ArgumentException($"Is null, empty, or whitespace.", nameof(filename))
: string.IsNullOrEmpty(replaceInvalidCharsWith)
? throw new ArgumentException($"Is null or empty.", nameof(replaceInvalidCharsWith))
: filename.All(c => c == '.')
? throw new ArgumentException($"Consists only of dots", nameof(filename))
: replaceInvalidCharsWith.All(c => c == '.')
? throw new ArgumentException($"Consists only of dots.", nameof(replaceInvalidCharsWith))
: replaceInvalidCharsWith.IndexOfAny(_invalidFileNameChars) != -1
? throw new ArgumentException($"Contains invalid filename chars.", nameof(replaceInvalidCharsWith))
: Regex.Replace(filename.Trim(), $"[{Regex.Escape(new(_invalidFileNameChars))}]", replaceInvalidCharsWith,
RegexOptions.Compiled | RegexOptions.CultureInvariant);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment