Snippets

Craig Phillips RandomString - A class containing methods to produce some handy random string combinations.

Created by Craig Phillips

File RandomString.cs Added

  • Ignore whitespace
  • Hide word diff
+using System;
+using System.Text;
+
+namespace RandomString
+{
+    public class RandomString : IDisposable
+    {
+		// Can use the BetterRandom class here or just use the built-in System.Random class.
+        private BetterRandom random = new BetterRandom();
+        private const string alpha_selection = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
+        private const string numeric_selection = "1234567890";
+        private const string symbol_selection = "!£$%^&*()-+=";
+
+        public string GenerateRandomString()
+        {
+            var length = random.Next(5, 15);
+            return GenerateRandomString(length);
+        }
+
+        public string GenerateRandomString(int length, bool onlyUseAlphaNumerics = false)
+        {
+            var alphanumeric_selection = alpha_selection + numeric_selection;
+            var characterSelection = onlyUseAlphaNumerics ? alphanumeric_selection : alphanumeric_selection + symbol_selection;
+            return GenerateRandomString(length, characterSelection);
+        }
+
+        public string GenerateRandomString(int length, string characterSelection)
+        {
+            var result = new StringBuilder();
+            for (var i = 0; i < length; i++)
+            {
+                var chr = characterSelection.Substring(random.Next(0, characterSelection.Length), 1);
+                result.Append(chr);
+            }
+            return result.ToString();
+        }
+
+        public string GenerateHashString(string stringToHash)
+        {
+            using (var crypto = new System.Security.Cryptography.SHA1CryptoServiceProvider())
+            {
+                return BitConverter.ToString(crypto.ComputeHash(Encoding.Unicode.GetBytes(stringToHash))).Replace("-", string.Empty);
+            }
+        }
+
+        public string GenerateRandomHashString()
+        {
+            return GenerateHashString(GenerateRandomString(1024));
+        }
+
+
+        public void Dispose()
+        {
+            Dispose(true);
+        }
+
+        protected virtual void Dispose(bool disposing)
+        {
+            if (disposing)
+            {
+                if (random != null)
+                {
+                    random.Dispose();
+                    random = null;
+                }
+            }
+            GC.SuppressFinalize(this);
+        }
+    }
+}
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.