NamespaceSystemLibrary.Common.Net.Global SystemLibrary.Common.Net.dll
This class contains extension methods for string
StringExtensions exists in the global namespace
StringExtensions
public static class StringExtensions
Inheritance
Examples
var result = "Hello world".Is()
// result is 'true'
var result = "".IsNot();
// result is 'true'
Arguments
Methods
Compress the input data and return
Remarks
Returned value might be larger if the input is only a character or two.
public static string Compress(this string data, Encoding encoding = null)
var data = "Hello world";
var compressed = data.Compress();
Methods arguments
Type | Name | Description |
---|---|---|
System.String | data | |
System.Text.Encoding | encoding |
Type | Description |
---|---|
System.String | Compressed version of input as Base64, or null/empty if input was so |
Check if text contains any of the values, case sensitive
public static bool ContainsAny(this string text, params string[] values)
var text = "hello";
var result = text.ContainsAny("123", "!", "lo");
// result is true, because lo is part of the text
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.String[] | values |
Type | Description |
---|---|
System.Boolean | True or false |
Check if text contains any of the values, case sensitive, with a string comparison
public static bool ContainsAny(this string text, StringComparison comparison, params string[] values)
var text = "hello";
var result = text.ContainsAny(StringComparison.Ordinal, "123", "!", "lo");
// result is true, because lo is part of the text
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.StringComparison | comparison | |
System.String[] | values |
Type | Description |
---|---|
System.Boolean | True or false |
Decompress compressed data and return the result
public static string Decompress(this string compressedData, Encoding encoding = null)
var data = "Hello world";
var compressed = data.Compress();
var decompressed = compressed.Decompress();
Assert.IsTrue(data == decompressed);
Methods arguments
Type | Name | Description |
---|---|---|
System.String | compressedData | A base64 compressed version of data |
System.Text.Encoding | encoding |
Type | Description |
---|---|
System.String | Decompressed version of input, or null/empty if input was so |
Returns the decrypted version of the cipher text
Remarks
Must pass same arguments as you did when you invoked .Encrypt()
'addedIV' must be true if you set 'addIV' to 'true' during Encrypt()
public static string Decrypt(this string cipherText, bool addedIV = true)
var data = "Hello world";
var encrypted = data.Encrypt();
var decrypted = encrypted.Decrypt();
Methods arguments
Type | Name | Description |
---|---|---|
System.String | cipherText | |
System.Boolean | addedIV |
Type | Description |
---|---|
System.String | Decrypted string or null/empty if input was so |
Returns the decrypted version of the cipher text
Remarks
Must pass same arguments as you did when you invoked .Encrypt()
'addedIV' must be true if you set 'addIV' to 'true' during Encrypt()
public static string Decrypt(this string cipherText, byte[] key, byte[] IV = null, bool addedIV = false)
var key = "16 or 32 chars...".GetBytes();
var data = "Hello world";
var encrypted = data.Encrypt(key);
var decrypted = encrypted.Decrypt(key);
Methods arguments
Type | Name | Description |
---|---|---|
System.String | cipherText | |
System.Byte[] | key | |
System.Byte[] | IV | |
System.Boolean | addedIV |
Type | Description |
---|---|
System.String | Decrypted string or null/empty if input was so |
Returns the decrypted version of the cipher text
Remarks
Must pass same arguments as you did when you invoked .Encrypt()
'addedIV' must be true if you set 'addIV' to 'true' during Encrypt()
public static string Decrypt(this string cipherText, string key, string IV = null, bool addedIV = false)
var key = "16 or 32 chars...";
var data = "Hello world";
var encrypted = data.Encrypt(key);
var decrypted = encrypted.Decrypt(key);
Methods arguments
Type | Name | Description |
---|---|---|
System.String | cipherText | |
System.String | key | |
System.String | IV | |
System.Boolean | addedIV |
Type | Description |
---|---|
System.String | Decrypted string or null/empty if input was so |
Decrypt data that was Encrypted through 'EncryptUsingKeyRing'
Uses the Data Protection API from Microsoft, which uses your setup of the AddDataProtection() services.
public static string DecryptUsingKeyRing(this string data)
var text = "hello world"; var cipherText = text.EncryptUsingKeyRing(); var textAgain = cipherText.DecryptUsingKeyRing();
Methods arguments
Type | Name | Description |
---|---|---|
System.String | data |
Type | Description |
---|---|
System.String |
Deobfuscate a string back to its readable state with a salt
Remarks
Returns the text as it was before obfuscating, assuming you used the same salt value
public static string Deobfuscate(this string text, int salt = 11)
var value = "Hello world";
var obfuscatedText = value.Obfuscate();
var deobfuscatedText = obfuscatedText.Deobfuscate();
// value == deobfuscatedText
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.Int32 | salt |
Type | Description |
---|---|
System.String | String or null/empty if input was so |
Encrypt data with a random generated IV
Key: If DataProtection has been setup
If key file is used, uses the filenameElse appName if set through SetApplicationName()
Else assembly nameElse no data protection usage: ABCDEFGHIJKLMNOPQRST123456789011
Remarks
- Data protection key file is a XML file, file name starts with "key-"
- Built-in keys are always hashed before used as the Key
- Optionally add a random IV as the first 16 bytes of output. If you dont, the IV is 16 bytes of 0public static string Encrypt(this string data, bool addIV = true)
var data = "Hello world";
var encrypted = data.Encrypt();
Methods arguments
Type | Name | Description |
---|---|---|
System.String | data | |
System.Boolean | addIV | Add the generated IV to the output or not |
Type | Description |
---|---|
System.String | Encrypted base64 string with IV in first 16 bytes, or null/empty if input was so |
Encrypt data with a key and an optional IV
Key is null?: If DataProtection has been setup
If key file is used, uses the filenameElse appName if set through SetApplicationName()
Else assembly nameElse no data protection usage: ABCDEFGHIJKLMNOPQRST123456789011
Optional IV: If IV is not set then use either; random IV if addIV is true else 16 bytes of 0Remarks
- Key must be 16 or 32 characters
- Optionally add IV to the fist 16 bytes of output, if not? IV is 16 bytes of 0
public static string Encrypt(this string data, byte[] key, byte[] IV = null, bool addIV = false)
var key = "16 or 32 chars...".GetBytes();
var data = "Hello world";
var encrypted = data.Encrypt(key);
Methods arguments
Type | Name | Description |
---|---|---|
System.String | data | |
System.Byte[] | key | |
System.Byte[] | IV | |
System.Boolean | addIV | Add the generated IV to the output or not |
Type | Description |
---|---|
System.String | Encrypted base64 string with IV in first 16 bytes if 'addIV' was true, or null/empty if input was so |
Encrypt data with a key and an optional IV
Key is null?: If DataProtection has been setup
If key file is used, uses the filenameElse appName if set through SetApplicationName()
Else assembly nameElse no data protection usage: ABCDEFGHIJKLMNOPQRST123456789011
Optional IV: If IV is not set then use either; random IV if addIV is true else 16 bytes of 0Remarks
- Key must be 16 or 32 characters
- Optionally add IV to the fist 16 bytes of output, if not? IV is 16 bytes of 0
public static string Encrypt(this string data, string key, string IV = null, bool addIV = false)
var key = "16 or 32 chars...";
var data = "Hello world";
var encrypted = data.Encrypt(key);
Methods arguments
Type | Name | Description |
---|---|---|
System.String | data | |
System.String | key | |
System.String | IV | |
System.Boolean | addIV | Add the generated IV to the output or not |
Type | Description |
---|---|
System.String | Encrypted base64 string with IV in first 16 bytes if 'addIV' was true, or null/empty if input was so |
Encrypt data which can be Decrypted through 'DecryptUsingKeyRing'
Uses the Data Protection API from Microsoft, which uses your setup of the AddDataProtection() services.
public static string EncryptUsingKeyRing(this string data)
var text = "hello world"; var cipherText = text.EncryptUsingKeyRing();
Methods arguments
Type | Name | Description |
---|---|---|
System.String | data |
Type | Description |
---|---|
System.String |
Returns true if text ends with any of the values, case sensitive
public static bool EndsWithAny(this string text, params string[] values)
var text = "hello world";
var result = text.EndsWithAny("", "abdef", "rld");
// result is true, because the last part of text ends with rld
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.String[] | values |
Type | Description |
---|---|
System.Boolean | True or false |
Returns true if text ends with any of the values, case sensitive, using StringComparison.Ordinal
public static bool EndsWithAny(this string text, StringComparison comparison, params string[] values)
var text = "hello world";
var result = text.EndsWithAny(StringComparison.Ordinal, "", "abdef", "rld");
// result is true, because the last part of text ends with rld
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.StringComparison | comparison | |
System.String[] | values |
Type | Description |
---|---|
System.Boolean | True or false |
Check if text ends ends with any characters from another string, case insensitive
public static bool EndsWithAnyCharacter(this string text, string characters)
var text = "hello world";
var result = text.EndsWithAnyCharacter("abcdef");
// result is true, because it ends with 'd'
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.String | characters | Each character in this string will be checked |
Type | Description |
---|---|
System.Boolean | True or false |
Convert base64string back to a normal string
public static string FromBase64(this string base64String, Encoding encoding = null)
var value = "Hello world";
var base64string = value.ToBase64();
var valueAgain = base64string.FromBase64();
// value == valueAgain
Methods arguments
Type | Name | Description |
---|---|---|
System.String | base64String | |
System.Text.Encoding | encoding |
Type | Description |
---|---|
System.String | String or null/empty if input was so |
Returns the base64string input as a byte array
public static byte[] FromBase64AsBytes(this string base64String)
Methods arguments
Type | Name | Description |
---|---|---|
System.String | base64String |
Type | Description |
---|---|
System.Byte[] | String or null/empty if input was so |
Returns the byte representation of the text
public static byte[] GetBytes(this string text, Encoding encoding = null)
var value = "Hello world";
var bytes = value.GetBytes();
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.Text.Encoding | encoding |
Type | Description |
---|---|
System.Byte[] | Byte array or null if input was null/empty |
Returns the domain part of the uri or blank, never null, includes ".com":
https://www.sub1.sub2.domain.com => domain.com
public static string GetPrimaryDomain(this string url)
var result = new Uri('https://systemlibrary.com/image?q=90&format=jpg').GetPrimaryDomain();
// result is "systemlibrary.com"
var result = new Uri('https://systemlibrary.github.io/systemlibrary-common-net/image?q=90&format=jpg').GetPrimaryDomain();
// result is "github.io"
Methods arguments
Type | Name | Description |
---|---|---|
System.String | url |
Type | Description |
---|---|
System.String | Primary domain or blank, never null |
Darken or lighten a hex value by a factor
- pass a positive factor to darken
- pass a negative factor to lighten
- factor is a number between 0 and 1
- pass auto: true, to automatically check difference in the new value, and if the diff is too small (almost same color), the value is rather darkened instead of lightened, or ligtened instead of darkened
public static string HexDarkenOrLighten(this string hex, double factor = 0.31, bool auto = false)
var value = "#FFF";
var newValue = value.HexDarkenOrLighten();
// newValue is #4F4F4F
Methods arguments
Type | Name | Description |
---|---|---|
System.String | hex | |
System.Double | factor | |
System.Boolean | auto |
Type | Description |
---|---|
System.String | A new hex darkened or lightend, or null/blank if input was so |
Html decode input and return the result
Example: ampersandGT; becomes >
public static string HtmlDecode(this string htmlEncodedText)
var html = "ampersand gt;";
var encoded = html.HtmlDecode();
// result equals >
// assume ampersand is the character, Microsofts Docfx has a ton of limits and their tactic to go with XML is to vomit of
Methods arguments
Type | Name | Description |
---|---|---|
System.String | htmlEncodedText |
Type | Description |
---|---|
System.String | HtmlDecoded version of input, if input is null/empty it returns null/empty |
Html encode input and return the result
Example: > becomes ampersandGT;
public static string HtmlEncode(this string text)
var html = ">";
var encoded = html.HtmlEncode();
// result contains ampersand gt;
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text |
Type | Description |
---|---|
System.String | HtmlEncoded version of input, if input is null/empty it returns null/empty |
Check if string is not null, "" and " "
Remarks
It does not check multiple spaces or new lines or tabs
public static bool Is(this string text)
// Old way: string.IsNullOrWhiteSpace(text);
var text = "hello world";
var result = text.Is();
// result is true because text is set to something, and not just "" or " "
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text |
Type | Description |
---|---|
System.Boolean | True or false |
Check if string is not null, "" and " " and not any of the 'invalidTexts', else false
Case sensitive
public static bool Is(this string text, params string[] invalidTexts)
var text = "hello world";
var result = text.Is("hello");
// result is true because text is set to something else than 'hello', and not just "" or " "
var result2 = text.Is("hello world");
// result is false, because text equals to the invalid text passed in, which was 'hello world'
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.String[] | invalidTexts |
Type | Description |
---|---|
System.Boolean | True or false |
Returns true if text equals any of the values, case sensitive
public static bool IsAny(this string text, params string[] values)
var text = "hello world";
var result = text.IsAny("hello", "world", "hello WORLD", "hello world");
// result is true, as the last 'hello world' matches exactly
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.String[] | values |
Type | Description |
---|---|
System.Boolean | True or false |
Checks if input is a file path, either relative or absolute, either web or operative system path
Remarks
Does not throw
Returns true if input is longer than 4, and contains a 'file extension' of 1 to 6 characters, else false
Returns true if input contains /public/, /static/, /images/ or 'assets/' as we assume a file is asked for
Supports input as relative, absolute, and with url query params
Returns false if input exceeds 4096 characters
public static bool IsFile(this string path)
var hello = "world";
var isFile = hello.IsFile(); // false
var file = "/image/redcar1.jpg?qualit=80";
var isFile = file.IsFile(); // true
var file2 = "/assets/bluecar";
var isFile = file2.IsFile(); // true, assumes any "assets/" request is a file
Methods arguments
Type | Name | Description |
---|---|---|
System.String | path |
Type | Description |
---|---|
System.Boolean | True or false |
Check if input is a valid json beginning
public static bool IsJson(this string data)
var data = "Hello world"; var isJson = data.IsJon(); // False
Methods arguments
Type | Name | Description |
---|---|---|
System.String | data |
Type | Description |
---|---|
System.Boolean | True or false |
Check if string is null, "" or " "
Remarks
Example says "old way string.NullOrWhitespace", but it does not check multi spaces nor tabs, nor new lines, so not exactly the same
public static bool IsNot(this string text, params string[] additionalNotValues)
//Old way: string.IsNullOrWhiteSpace(text);
var text = " ";
var result = text.IsNot();
// result is true because a single space counts as "no text" in this function
var text = " "; //2 spaces
var result = text.IsNot();
// result is false because two spaces counts as text in this function
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.String[] | additionalNotValues |
Type | Description |
---|---|
System.Boolean | True or false |
Convert string formatted json to object T
Default options are:
- case insensitive deserialization
- allows trailing commas
Throws exception if json has invalid formatted json text, does not throw on null/blankpublic static T Json<T>(this string json, JsonSerializerOptions options = null, bool transformUnicodeCodepoints = false) where T : class
class User {
public string FirstName;
public int Age { get; set;}
}
var json = "{
"firstName": 'hello',
"age": 10
}";
var user = json.Json<User>();
// NOTE: Naming is camelCase'd in json, but still matched (case insensitive) during deserialization by default
Generic types
Name | Description |
---|---|
T |
Methods arguments
Type | Name | Description |
---|---|---|
System.String | json | |
System.Text.Json.JsonSerializerOptions | options | |
System.Boolean | transformUnicodeCodepoints |
Type | Description |
---|---|
T | Returns T or null if json is null or empty |
Convert string formatted json to object T with your additional JsonConverters
Throws exception if json has invalid formatted json text, does not throw on null/blank
public static T Json<T>(this string json, params JsonConverter[] converters) where T : class
class User {
public string FirstName;
public int Age { get; set;}
}
class CustomConverter : JsonConverter...
var json = "{
"firstName": 'hello',
"age": 10
}";
var user = json.Json<User>(new CustomConverter());
// NOTE: Naming is camelCase'd in json, but still matched (case insensitive) during deserialization by default
Generic types
Name | Description |
---|---|
T |
Methods arguments
Type | Name | Description |
---|---|---|
System.String | json | |
System.Text.Json.Serialization.JsonConverter[] | converters |
Type | Description |
---|---|
T | Returns T or null if json is null or empty |
Return a part of the json as T
Searches through the json looking for a property that has the same name as T type, and outputs T
Supports taking a 'search property path' seperated by a forward slash to the leaf property you want to convert to T, case insensitive
Throws if a node towards the leaf is not found when specifying a 'search property path'
Throws if json has invalid formatted json text, does not throw on null/blankpublic static T JsonPartial<T>(this string json, string findPropertySearchPath = null, JsonSerializerOptions options = null)
// Assume json string stored in a C# variable named 'data':
var data = "{
"users" [
...
]
}";
var users = data.JsonPartial<List<User>>();
// When a 'property name' is not given as first argument, it uses the type name in the following manner:
// 1. Takes the type name, or generic type name, in our case 'User'
// 2. If type is a List or Array, it adds a plural 's', so now we have 'Users'
// 3. It lowers first letter to match camel casing as thats the "norm", so now we have 'users'
// You could also pass in "users" manually if you wanted, result is the same:
// var users = data.JsonPartial<List<User>>("users");
// Conclusion:
// Automatic finding the property name if not specified as first argument
// It returns first "users" match in the json, no matter how deep it is
//Assume json string stored in a C# variable named 'data':
var data = "{
"users" [
...
],
"deactivated": {
"users": [
...
]
}
}";
var users = data.JsonPartial<List<User>>("deactivated/users");
// Searches for a property "deactivated" anywhere in the json, then anywhere inside that, a "users" property
// Assume json string stored in a C# variable named 'data':
var data = "{
"text": "hello world",
"employees": [
{
"hired": [
...
],
"fired": [
...
]
}
],
}";
var users = data.JsonPartial<List<User>>("fired");
// Searches for a property anywhere in the json named "fired"
Generic types
Name | Description |
---|---|
T | A class or list/array of a class If T is a list or array and no 'findPropertySearchPath' is specified, the Searcher appends an 's' as suffix For instance List<User> will search for a property 'users', case insensitive and 's' is appended |
Methods arguments
Type | Name | Description |
---|---|---|
System.String | json | Json formatted string |
System.String | findPropertySearchPath | Name of the property that will be deserialized as T Example: root/property1/property2/leaf where 'leaf' will be deserialized as T |
System.Text.Json.JsonSerializerOptions | options |
Type | Description |
---|---|
T | Returns T or null if the leaf property do not exist |
Check if string is longer and returns a substring up to MaxLength
public static string MaxLength(this string text, int maxLength)
var text = "hello world";
var result = text.MaxLength(1);
// result is "h" as it only can be 1 character long
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.Int32 | maxLength |
Type | Description |
---|---|
System.String | Returns the string as it is if text is blank/null or shorter than maxLength, else returns a substring with a length of 'maxLength'. If maxLength is negative it returns "" |
Obfuscate a string to a different string with a salt
Throws exception if salt is <= 0, salt should be in range from 1 to 65000
Remarks
Method .ToBase64() is faster if data is more than 400KB
public static string Obfuscate(this string text, int salt = 11)
var value = "Hello world";
var obfuscatedText = value.Obfuscate();
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.Int32 | salt |
Type | Description |
---|---|
System.String | String or null/empty if input was so |
Returns data or the first fallback that exists
If all subsequent fallbacks are null, this returns ""
public static string OrFirstOf(this string text, params string[] fallbacks)
var text1 = null;
var text2 = "";
var text3 = " ";
var text4 = "hello";
var result = text1.OrFirstOf(text2, text3, text4);
// result is "hello" as the others are blank/empty
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.String[] | fallbacks |
Type | Description |
---|---|
System.String | First non-null, non-empty and non-space string value, or empty string, never null. |
Returns a new string where all 'old values' are replaced with the 'newValue'
Does not throw on argument null
public static string ReplaceAllWith(this string text, string newValue, params string[] oldValues)
var text = "Hello world 12345";
var result = text.ReplaceAllWith("A", "Hello", "World", "123", "45");
// result == A A AA, all mathing texts are replaces with the first param 'A'
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.String | newValue | |
System.String[] | oldValues |
Type | Description |
---|---|
System.String | A new string with all replacements |
Returns true if text starts with any of the values, case sensitive
public static bool StartsWithAny(this string text, params string[] values)
var text = "hello world";
var result = text.StartsWithAny("", "abcdef", "hel");
// result is true, due to the text begins with 'hel'
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.String[] | values |
Type | Description |
---|---|
System.Boolean | True or false |
Returns true if text starts with any of the values, case sensitive, using a String Comparison
public static bool StartsWithAny(this string text, StringComparison comparison, params string[] values)
var text = "hello world";
var result = text.StartsWithAny(StringComparison.Ordinal, "", "abcdef", "hel");
// result is true, due to the text begins with 'hel'
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.StringComparison | comparison | |
System.String[] | values |
Type | Description |
---|---|
System.Boolean | True or false |
Convert input to its Base64
Remarks
If you dont need base64 format, .Obfuscating() method is faster if data is less than ~400KB
public static string ToBase64(this string text, Encoding encoding = null)
var value = "Hello world";
var base64string = value.ToBase64();
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.Text.Encoding | encoding |
Type | Description |
---|---|
System.String | Base64 string, or null or blank if input was so |
Returns string as camel cased
Each word's first letter is upper case
- words after a space or a dash
- except the very first letter, it is lower cased
All other letters are lower cased
public static string toCamelCase(this string text)
var text = "abC deF";
var result = text.ToPascalCase();
//result == "abc Def"
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text |
Type | Description |
---|---|
System.String | camelCased version of input, or null/blank if input was so |
Converts input date to a DateTime by trying different formats till successfully converted or throwing exception
public static DateTime ToDateTime(this string date, string format = null)
var date = "2000-12-24";
var dateTime = date.ToDateTime();
Methods arguments
Type | Name | Description |
---|---|---|
System.String | date | |
System.String | format |
Type | Description |
---|---|
System.DateTime | Returns DateTime.MinValue if input is too short |
Converts input date to a DateTimeOffset by trying different formats till successfully converted or throwing exception
public static DateTimeOffset ToDateTimeOffset(this string date, string format = null)
var date = "2000-12-24";
var dateTime = date.ToDateTimeOffset();
Methods arguments
Type | Name | Description |
---|---|---|
System.String | date | |
System.String | format |
Type | Description |
---|---|
System.DateTimeOffset | Returns DateTimeOffset.MinValue if input is too short |
Convert a string to the Enum Type and cast as Object on returnal
public static object ToEnum(this string text, Type enumType)
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.Type | enumType |
Type | Description |
---|---|
System.Object | Returns first match or the first Key in the Enum |
Convert a string value to Enum
public static T ToEnum<T>(this string text) where T : struct, IComparable, IFormattable, IConvertible
enum EnumColor
{
None,
[EnumText("White")]
[EnumValue("BlackAndWhite")]
Black,
Pink
}
var value = "black".ToEnum<EnumColor>();
// value is EnumColor.Black, case insensitive match directly in the Enum Key (or name if you prefer)
var value = "white".ToEnum<EnumColor>();
// value is EnumColor.Black, case insensitive match in 'EnumText' attribute
var value = "blackAndWhite".ToEnum<EnumColor>();
// value is EnumColor.Black, case insensitive match in 'EnumValue' attribute
var value = "brown".ToEnum<EnumColor>();
// value is EnumColor.None, no match, returns first enum Key
Generic types
Name | Description |
---|---|
T | T must be an Enum |
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | Value must match the Key or the 'EnumValueAttribute' or 'EnumTextAttribute' of a Key in the Enum (EnumValue is checked before EnumText), else this returns default of the Enum T |
Type | Description |
---|---|
T | Returns first matching Key or default of the Enum |
Convert string to integer
Returns 0 on empty/null strings
Throws if string is not a numberpublic static int ToInt(this string number)
Methods arguments
Type | Name | Description |
---|---|---|
System.String | number |
Type | Description |
---|---|
System.Int32 | Converted string as Integer |
Convert string to Int64
Returns 0 on empty/null strings
Throws if string is not a numberpublic static long ToInt64(this string number)
Methods arguments
Type | Name | Description |
---|---|---|
System.String | number |
Type | Description |
---|---|
System.Int64 | Converted string as Int64 |
Returns a new string with digits and letters only
Question marks, commas, exclamation marks, etc, are removed
public static string ToLetterAndDigits(this string text)
var email = "support@system.library.com";
var text = email.ToLetterAndDigits();
// text is "supportsystemlibrarycom"
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text |
Type | Description |
---|---|
System.String | String with digits and characters, or blank if input is null or empty |
Returns a MD5 hash version of the text input, resulting in a 47 character long text (including dashes).
Remarks
If data is larger than ~200 bytes then .ToSha1Hash() is faster Md5 is not secure, there are rainbow tables, it's a 'one way shrinking obfuscater'
public static string ToMD5Hash(this string text)
var value = "Hello world";
var md5text = value.ToMD5Hash();
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text |
Type | Description |
---|---|
System.String | Md5 hash string or null/empty if input was so |
Returns string as pascal cased, each character after a space or a dash is upper cased, while all others are forced lower cased
public static string ToPascalCase(this string text)
var text = "abC deF";
var result = text.ToPascalCase();
//result == "Abc Def"
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text |
Type | Description |
---|---|
System.String | string pascal cased or null/empty if input was so |
Convert any uri to a application url, targetting files/folders inside your running app
Assume app is hosted in C:/www/syslib/
Examples: http://www.systemlibrary.com/a returns C:\www\syslib\a a returns C:/www/syslib/a /a returns C:/www/syslib/a a/ returns C:/www/syslib/a/ /a/ returns C:/www/syslib/a/ \a returns C:/www/syslib/a \a\b\ returns C:/www/syslib/a/b/
If input ends with slash, return value ends with slash
Remarks
Always returns URL's with forward slashes
Server Root Path is read from CurrentDomain["ContentRootPath"] with fallback to AppContext.BaseDirectory.Parent. If a folder in the returning path is /bin/ it will navigate to the parent of such a folder then return
Remember that a URL is not a browser specific term, Uniform Resource Locatorpublic static string ToPhysicalPath(this string path)
var text = "/hello/world.txt";
var result = text.ToPhysicalPath();
// result == "C:/pub/www/hello/world.txt"
var text2 = "https://www.syslib.com/hello";
var result2 = text2.ToPhysicalPath();
// result2 == "C:/www/hello", no ending slash as text2 did not contain it
Methods arguments
Type | Name | Description |
---|---|---|
System.String | path |
Type | Description |
---|---|
System.String | Absolute application url based on input 'path', or null or empty if input was so |
Returns a Sha1 hash version of the text input, resulting in a 59 character long text (including dashes).
Remarks
If data is smaller than ~200 bytes then .ToMD5Hash() is faster Sha1 is not secure, there are rainbow tables, it's a 'one way shrinking obfuscater'
public static string ToSha1Hash(this string text)
var value = "Hello world";
var sha1 = value.ToSha1Hash();
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text |
Type | Description |
---|---|
System.String | Sha1 hash string or null/empty if input was so |
Returns a Sha256 hash version of the text input
public static string ToSha256Hash(this string text)
var value = "Hello world";
var sha1 = value.ToSha1Hash();
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text |
Type | Description |
---|---|
System.String | Sha256 hash string or null/empty if input was so |
Convert input to Utf8 BOM
public static string ToUtf8BOM(this string text)
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text |
Type | Description |
---|---|
System.String | A new string Utf8BOM encoded |
Translate unicode code points to characters
Example: HellU+00F8 is converted into Hellø (NOR char oslash;)
and
Hell\u00F8 is converted also into Hellø (NOR char oslash;)
public static string TranslateUnicodeCodepoints(this string data)
Methods arguments
Type | Name | Description |
---|---|---|
System.String | data |
Type | Description |
---|---|
System.String | Translated text |
Trim the end of a string if it ends with any of the inputs
- It does not trim spaces, you must specify it as argument
- Not recursive, returns after the first trimming
- Case sensitivepublic static string TrimEnd(this string text, params string[] values)
var result = "abcd".TrimEnd(" ", "!", "c", "d");
// result is abc
var result = "abcd".TrimEnd(" ", "d", "bc");
// result is "abc" because it matches 'd' then returns, so 'bc' is never checked
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text | |
System.String[] | values |
Type | Description |
---|---|
System.String | Returns the input string as is or without first value matched as ending |
Returns uri decoded version of a uri encoded string
Example: For instance: %20 becomes 'space', and %2B becomes '+'
public static string UriDecode(this string text)
var coded = "Hello%20world%20%2B%20%3F";
var plain = coded.UriDecode();
//plain == "Hello world + ?"
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text |
Type | Description |
---|---|
System.String | Uri decoded or null/blank if input was so |
Returns uri encoded version of a string, usually safe as a query parameter in a url for instance
For instance: A 'space' becomes %20, and a '+' sign becomes %2B
public static string UriEncode(this string text)
var plain = "Hello world + ?";
var coded = plain.UriEncode();
//coded == "Hello%20world%20%2B%20%3F"
Methods arguments
Type | Name | Description |
---|---|---|
System.String | text |
Type | Description |
---|---|
System.String |
}