Skip to content

Instantly share code, notes, and snippets.

@sergiorykov
Created September 1, 2016 14:57
Show Gist options
  • Save sergiorykov/219605a220edf80d4b55fe87a9f92b38 to your computer and use it in GitHub Desktop.
Save sergiorykov/219605a220edf80d4b55fe87a9f92b38 to your computer and use it in GitHub Desktop.
Sanitized File Name C#
using System.IO;
using System.Text.RegularExpressions;
namespace Mojito.Core
{
public class SanitizedFileName
{
// https://msdn.microsoft.com/en-us/library/aa365247.aspx#naming_conventions
// http://stackoverflow.com/questions/146134/how-to-remove-illegal-characters-from-path-and-filenames
private static readonly Regex removeInvalidChars = new Regex($"[{Regex.Escape(new string(Path.GetInvalidFileNameChars()))}]",
RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);
public SanitizedFileName(string fileName, string replacement = "_")
{
Check.NotNull(fileName, nameof(fileName));
Value = removeInvalidChars.Replace(fileName, replacement);
}
public string Value { get; }
}
}
using Shouldly;
using Mojito.Core;
using Xunit;
namespace UnitTests.Core
{
public class SanitizedFileNameTests
{
[Theory]
[InlineData("asdf.txt", "asdf.txt")]
[InlineData("\"<>|:*?\\/.txt", "_________.txt")]
[InlineData("yes_its_valid_~!@#$%^&()_+.txt", "yes_its_valid_~!@#$%^&()_+.txt")]
public void Sanitize_SpecifiedFileName_ValueAsExpected(string fileName, string expectedSanitized)
{
// https://msdn.microsoft.com/en-us/library/aa365247.aspx#naming_conventions
var sanitized = new SanitizedFileName(fileName);
sanitized.Value.ShouldBe(expectedSanitized);
}
[Fact]
public void Sanitize_WithCustomReplacement_ReplacedAsExpected()
{
var sanitized = new SanitizedFileName("*_*.txt", "Yo");
sanitized.Value.ShouldBe("Yo_Yo.txt");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment