From d5cf549435c303c8f3b41690fc7386975350d7d7 Mon Sep 17 00:00:00 2001 From: Serraniel Date: Mon, 17 Apr 2017 11:31:46 +0200 Subject: [PATCH] Added general utils class. Implemented functions for file name legalization. --- SweetLib/SweetLib.csproj | 1 + SweetLib/Utils/SweetUtils.cs | 43 ++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 SweetLib/Utils/SweetUtils.cs diff --git a/SweetLib/SweetLib.csproj b/SweetLib/SweetLib.csproj index f6c11d4..e612631 100644 --- a/SweetLib/SweetLib.csproj +++ b/SweetLib/SweetLib.csproj @@ -51,6 +51,7 @@ + diff --git a/SweetLib/Utils/SweetUtils.cs b/SweetLib/Utils/SweetUtils.cs new file mode 100644 index 0000000..57e2a2a --- /dev/null +++ b/SweetLib/Utils/SweetUtils.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SweetLib.Utils +{ + /// + /// A generic class containing useful methods. + /// + public static class SweetUtils + { + public static char DefaultFileNameReplaceChar { get; set; } = '-'; + + /// + /// Legalizes a file name with the character. + /// + /// File name to legalize. + /// Legalized file name. + public static string LegalizeFilename(string fileName) + { + return LegalizeFilename(fileName, '-'); + } + + /// + /// Legalizes a file name by a given replace character. + /// + /// File name to legalize. + /// Character to be used as replace character. + /// Legalized file name. + public static string LegalizeFilename(string fileName, char replaceChar) + { + var invalidChars = System.IO.Path.GetInvalidFileNameChars(); + + if(invalidChars.Contains(replaceChar)) + throw new IOException($"Replace character {replaceChar} is an invalid file name character."); + + return invalidChars.Aggregate(fileName, (current, c) => current.Replace(c, replaceChar)); + } + } +}