Skip to content

Instantly share code, notes, and snippets.

@5cover
5cover / FilenameHelpers.cs
Last active Nov 19, 2022
Create a valid NTFS Windows filename out of a string
View FilenameHelpers.cs
/// <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 = "_")