54 lines
1.9 KiB
C#
54 lines
1.9 KiB
C#
using System.IO;
|
|
using System.Linq;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace Alkami.Ops.Common.Extensions
|
|
{
|
|
public static class StringExtensions
|
|
{
|
|
private static readonly Regex Base64Regex = new Regex(
|
|
@"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=|[A-Za-z0-9+/][AQgw]==)?$",
|
|
RegexOptions.Compiled | RegexOptions.CultureInvariant);
|
|
|
|
/// <summary>
|
|
/// Determines if a string is base 64
|
|
/// </summary>
|
|
/// <param name="s"></param>
|
|
/// <returns></returns>
|
|
public static bool IsBase64String(this string s)
|
|
{
|
|
if (string.IsNullOrEmpty(s))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return (Base64Regex.IsMatch(s) && s.Length % 4 == 0);
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Removes characters that are invalid for a filename from a string
|
|
/// </summary>
|
|
/// <param name="fileName"></param>
|
|
/// <returns></returns>
|
|
public static string GetSanitizedFileName(this string fileName)
|
|
{
|
|
var invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
|
|
var invalidReStr = string.Format(@"[{0}]+", invalidChars);
|
|
|
|
var reservedWords = new[]
|
|
{
|
|
"CON", "PRN", "AUX", "CLOCK$", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4",
|
|
"COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4",
|
|
"LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
|
|
};
|
|
|
|
var sanitisedNamePart = Regex.Replace(fileName, invalidReStr, "_");
|
|
|
|
return reservedWords.Select(reservedWord => string.Format("^{0}\\.", reservedWord))
|
|
.Aggregate(sanitisedNamePart,
|
|
(current, reservedWordPattern) => Regex.Replace(current, reservedWordPattern, "_reservedWord_.", RegexOptions.IgnoreCase));
|
|
}
|
|
}
|
|
}
|