vendredi 10 janvier 2020

C# - Function to randomise case of four strings always returns each string in the same case

I'm trying to build a basic random password generator in a Windows form. I have a list of words (all lower case), four of which get picked at random. Each word gets passed to a function to randomly change the case (capitalise the first character, capitalise the entire word, or just return the string in lower case) and then added to another list like so:

var dictionary = new List<String> { "aaron", "abandoned", "aberdeen" etc... };
int index;
index = random.Next(dictionary.Count);
string one = dictionary[index];
one = randomCase(one);
pwarray.Add(one);

This code is then duplicated for strings two, three and four. My function to randomise the case while not fancy is as so:

        private string randomCase (string word)
        {
            string changed;
            Random r = new Random();
            int n = r.Next(1, 29);

            // Output number to check it's not the same each time
            MessageBox.Show(n.ToString());
            if (n >= 1 || n <= 9)
            {
                // First letter capatalised
                changed = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word.ToLower());
                return changed;
            }
            else if (n >= 10 || n <= 19)
            {
                // Word capitalised 
                changed = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word.ToUpper());
                return changed;
            }
            else if (n >= 20 || n <= 29)
            {
                // Word left as lower case
                return word;
            }

            return null;
        }

I've added output message boxes to show what random number n is to aid with troubleshooting. When I run the app, I get different numbers from my randomCase function for n:

enter image description hereenter image description hereenter image description hereenter image description here

4 - First character capitalised

17 - Word capitalised

20 - Word left as lower case

24 - word left as lower case

However all four words have had the first letter capitalised:

enter image description here:

I've generated many passwords and they always seem to come out in the same way - first letter capitalised only. Can anyone offer any suggestions?




Aucun commentaire:

Enregistrer un commentaire