mercredi 9 décembre 2020

Can someone help me understand why Random() is not working?

I'll preface this with I'm new to C#. This is SUPER simple in PowerShell, but I want to understand how to do it in C#. Here's the code, I'll explain what's not working.

        static void Main(string[] args)
        {
            var lena = 10; 
            string randomLowercase = Randomize("abcdefghijklmnopqrstuvwxyz",lena);
            
            var lenb =2;
            string randomUppercase = Randomize("ZYXWVUTSRQPONMLKJIHGFEDCBA", lenb);

            var lenc = 2;
            string randomNumbers = Randomize("0123456789", lenc);

            var lend = 2;
            string randomSpecChar = Randomize("!%&()?}][{@*", lend);

            string randomWord = randomLowercase + randomUppercase + randomNumbers + randomSpecChar;
            string randomPassword = Randomize(randomWord, randomWord.Length);

            Console.Write("Random Lowercase: {0}\nRandom Uppercase: {1}\nRandom Numbers: {2}\nRandom Special Characters: {3}\n", randomLowercase, randomUppercase, randomNumbers, randomSpecChar);
            
            Console.Write("\nRandom Word Length: {0}\nRandom Word: {1}\n", randomWord.Length, randomWord);
            Console.Write("\nRandom Password: {0}", randomPassword);
            
            Console.Read();
        }

       static string Randomize(string text, int len)
        {
            var chars = text;
            var stringChars = new char[len];
            var random = new Random();

            for (int i = 0; i<stringChars.Length; i++)
            {
                stringChars[i] = chars[random.Next(chars.Length)];
            }

            var output = new String(stringChars);
            return output;
        }
    }

This is what it outputs:

Random Lowercase: kmrdmcqxlh
Random Uppercase: PN
Random Numbers: 34
Random Special Characters: )?

Random Word Length: 16
Random Word: kmrdmcqxlhPN34)?

Random Password: qxPrxmP)qmml43Pl

The jumble-up of the 16 characters works - I get 'kmrdmcqxlhPN34)?'. But the last part breaks something. It drops one of the special characters - the '?', adds an extra 'P' and some other things.

The random word is fine - what could cause the error in the Randomize method? I'm thinking it's leftover values maybe?? Should I reset any variables when I exit the method?

Any help is appreciated!!




Aucun commentaire:

Enregistrer un commentaire