Gets a random string of a particular length - CSharp System

CSharp examples for System:Random

Description

Gets a random string of a particular length

Demo Code


using System.Text;
using System.Security.Cryptography;
using System.Net.Http.Formatting;
using System.IO;//from w w w. jav a  2 s .co  m
using System;

public class Main{
        /// <summary>
		/// Gets a random string of a particular length
		/// </summary>
		/// <param name="minLength">The minimum length of the string</param>
		/// <param name="maxLength">The maximum length of the string</param>
		/// <returns>A random string of characters</returns>
		public static string GetRandomString(int minLength = 6, int maxLength = 20)
		{
			if (minLength <= 0) throw new ArgumentException("Minimum Length must be greater than zero.");
			if (maxLength <= 0) throw new ArgumentException("Maximum Length must be greater than zero, and greater than Minimum Length.");
			if (maxLength < minLength) throw new ArgumentException("Maximum Length must be greater than Minimum Length.");

			int length = 0;
			string result = string.Empty;

			while (length < minLength || length > maxLength)
			{
				if (length > maxLength)
				{
					//Too long, need to trim it
					result = result.Substring(0, maxLength);
				}
				else
				{
					string random = Path.GetRandomFileName().Replace(".", "");
					result += random;
				}

				length = result.Length;
			}

			return result;
		}
}

Related Tutorials