To generate a random password in C#, you can use the Random
class along with a set of characters. Here is an example implementation:
main.cs417 chars15 lines
In this example, the GeneratePassword
method takes an integer argument length
which specifies the desired length of the password. The method uses a string of characters that can be included in the password, including upper and lower case letters, digits, and special characters.
Inside the method, we create a Random
object to generate random indices within the range of the characters string. We then loop length
number of times, randomly selecting a character from the string and appending it to a StringBuilder
object.
Finally, we return the generated password as a string by calling the ToString
method on the StringBuilder
object.
You can use this method like:
main.cs131 chars4 lines
Note that you may need to include using System.Text;
at the top of your code file to use the StringBuilder
class.
gistlibby LogSnag