Create a random string with a maximum length. - CSharp System

CSharp examples for System:Random

Description

Create a random string with a maximum length.

Demo Code


using System.Text;
using System.Security.Cryptography;
using System;/*  w w  w.java 2s . c  o  m*/

public class Main{
        /// <summary>
        /// Create a random string with a maximum length.
        /// </summary>
        /// <param name="length">Max length of random string</param>
        /// <returns>Generated string</returns>
        public static string GenerateRandomString(int length)
        {
            // Create a byte array as a data source
            byte[] tmpSource = Encoding.ASCII.GetBytes(DateTime.Now.Ticks.ToString());

            byte[] tmpHash = new SHA512Managed().ComputeHash(tmpSource);
            string result = Convert.ToBase64String(tmpHash);

            if (result.Length > length)
            {
                result = result.Substring(0, length);
            }

            return result;
        }
}

Related Tutorials