Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate random password for one-time password verification

I had to generate random password for temporary entry/login purpose in C#. Now I need to only send 6 digits but no more characters, or special characters. New to the C# world. Hence, I am providing what I have so far.

helper.cs

public static string GenerateRandomPassword()
{
    int numsLength = 6;
    
    const string nums = "0123456789";
    StringBuilder sb = new StringBuilder();
    Random rnd = new Random();

    for (int i = 0; i < charLength; i++)
    {
        int index = rnd.Next(chars.Length);
        sb.Append(chars[index]);
    }
    int numindex = rnd.Next(nums.Length);
    sb.Append(nums[numindex]);

    return sb.ToString();
}

I think my logic is still not right. I know that I should not use String Builder since I only want to send digits. Can anyone help me and figure out my mistake by editing the above codes?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could also just concatenate strings and do something like:

public static string GenerateRandomPassword()
{
    int numsLength = 6;

    const string nums = "0123456789";
    string tempPass = string.Empty;
    Random rnd = new Random();

    for (int i = 1; i <= numsLength; i++)
    {
        int index = rnd.Next(nums.Length);
        tempPass += nums[index];
    }

    return tempPass;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading