5
public void generate()
{
    string alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string small_alphabets = "abcdefghijklmnopqrstuvwxyz";
    string numbers = "1234567890";
    string characters = numbers;
    characters += alphabets + small_alphabets + numbers;

    int length =6;
    string opt = string.Empty;
    for (int i = 0; i < length; i++)
    {
        string character = string.Empty;
        do
        {
            int index = new Random().Next(0, characters.Length);
            character = characters.ToCharArray()[index].ToString();
        } while (otp.IndexOf(character) != -1);
        otp += character;
    }
    string str= otp;
}

This is my code, which is not working for me. I want to try small alphabet, capital alphabet and 0 to 9 number combination.

lbonn
  • 2,499
  • 22
  • 32
Manish Singh
  • 934
  • 1
  • 12
  • 27
  • 1
    1) You're creating a new instance of `Random` in a tight loop so it's probably getting the same seed. 2) Don't use `Random` in the first place. Use a CSPRNG from `RandomNumberGenerator.Create()`. 3) You didn't explain what "not working" means. – vcsjones Aug 29 '16 at 13:23
  • Can you elaborate on how your code "doesn't work"? What were you expecting, and what actually happened? If you got an exception/error, post the line it occurred on and the exception/error details. Please [edit] these details in or we may not be able to help. – gunr2171 Aug 29 '16 at 13:58
  • Possible duplicate of [How do I generate a random int number in C#?](http://stackoverflow.com/questions/2706500/how-do-i-generate-a-random-int-number-in-c) – Manish Singh Mar 29 '17 at 12:09

2 Answers2

9

Here is the code :

var chars1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
var stringChars1 = new char[6];
var random1 = new Random();

for (int i = 0; i < stringChars1.Length; i++)
{
    stringChars1[i] = chars1[random1.Next(chars1.Length)];
}

var str= new String(stringChars1);
Kyll
  • 7,036
  • 7
  • 41
  • 64
  • 5
    While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – gunr2171 Aug 29 '16 at 13:58
3

This code will give you numeric otp of n digits.

public static int GenerateOTP(int digits)
    {
        if (digits < 3)
            return new Random().Next(10, 99);
        else
            return new Random().Next(MultiplyNTimes(digits), MultiplyNTimes(digits + 1) - 1);
    }

private static int MultiplyNTimes(int n)
    {
        if (n == 1)
            return 1;
        else
            return 10 * MultiplyNTimes(n - 1);
    }
SilverNak
  • 3,283
  • 4
  • 28
  • 44