Get a string of random characters (a-z, A-Z, 0-9) of length n - CSharp System

CSharp examples for System:Random

Description

Get a string of random characters (a-z, A-Z, 0-9) of length n

Demo Code

//  Copyright by Contributors
using System.IO;// w ww  .  j  a va 2s  . c  om
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Text;
using System.Collections.Generic;
using System;

public class Main{
        /// <summary>
        /// Get a string of random characters (a-z, A-Z, 0-9) of length n
        /// </summary>
        /// <param name="n">The length of the random character string to generate</param>
        /// <returns>String of random characters of length n</returns>
        public static string getNCharRandom(int n)
        {
            char[] rndm = new char[n];
            char[] chars = new char[62];
            chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();

            for (int i = 0; i < n; i++)
            {
                rndm[i] = chars[StringRandom.Next(chars.Length)];
            }
            return new string(rndm);
        }
}

Related Tutorials