Last active
May 27, 2021 14:36
-
-
Save souzagustavo/cb7b8c7218c78c7bd75c2496c97f7abf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class StringExtension | |
{ | |
public static bool IsBase64(this string value) | |
{ | |
string pattern = @"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$"; | |
Regex rg = new Regex(pattern); | |
return rg.IsMatch(value); | |
} | |
public static string Base64Decode(this string value, bool returnSameValueIsNotBase64 = false) | |
{ | |
if (string.IsNullOrWhiteSpace(value)) | |
return null; | |
if ( (returnSameValueIsNotBase64) && !(value.IsBase64()) ) | |
return value; | |
var base64EncodedBytes = System.Convert.FromBase64String(value); | |
return Encoding.UTF8.GetString(base64EncodedBytes); | |
} | |
public static bool IsNumeric(this string value) | |
{ | |
if (string.IsNullOrWhiteSpace(value)) | |
return false; | |
return int.TryParse(value, out _); | |
} | |
public static string TryGetSubstring(this string value, int startIndex, int length) | |
{ | |
return TryGetSubstring(value, startIndex, length, false); | |
} | |
public static string TryGetSubstring(this string value, int startIndex, int length, bool returnOriginalValue) | |
{ | |
if (string.IsNullOrWhiteSpace(value) || value.Length < startIndex + length) | |
return returnOriginalValue ? value : string.Empty; | |
return value.Substring(startIndex, length); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment