Languages
[Edit]
EN

C# / .NET - random string (random text)

5 points
Created by:
Kate_C
2857

In C# / .NET it is possible to generate random text in few ways.

1. Random string example

public static class RandomUtils
{
	private static readonly string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
		"abcdefghijklmnopqrstuvwxyz" + 
		"0123456789";

	public static string generateText(int length)
	{
		Random random = new Random();
		StringBuilder builder = new StringBuilder(length);

		for (int i = 0; i < length; ++i)
		{
			int index = random.Next(ALPHABET.Length);

			builder.Append(ALPHABET[index]);
		}

		return builder.ToString();
	}
}

Example:

string value = RandomUtils.generateText(32);
Console.WriteLine(value);

Output:

inog93o8FXgBSy5kgali4RjF0JRUeMUf

2. Random characters example

public static class RandomUtils
{
	private static readonly string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
		"abcdefghijklmnopqrstuvwxyz" + 
		"0123456789";

	public static char[] generateChars(int length)
	{
		Random random = new Random();
		char[] result = new char[length];

		for (int i = 0; i < length; ++i)
		{
			int index = random.Next(ALPHABET.Length);

			result[i] = ALPHABET[index];
		}

		return result;
	}
}

Example:

char[] value = RandomUtils.generateChars(32);
Console.WriteLine(value);

Output:

atKK7quegNmtzHuKLK57kaVenhzsSCiA
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.