C# Program to Generate Random String

This is a C# Program to randomly generate strings.

Problem Description

This C# Program Randomly Generates Strings.

Problem Solution

Here strings are randomly generated using the random function.

Program/Source Code

Here is source code of the C# Program to Randomly Generate Strings. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Randomly Generate Strings
 */
using System;
using System.IO;
static class Random
{
    public static string GetRandomString()
    {
        string path = Path.GetRandomFileName();
        path = path.Replace(".", ""); 
        return path;
    }
}
class Program
{
    static void Main()
    {
        Console.WriteLine(Random.GetRandomString());
        Console.WriteLine(Random.GetRandomString());
        Console.WriteLine(Random.GetRandomString());
        Console.Read();
    }
}
Program Explanation

This C# program is used to generate random file names to store certain kinds of data. Using Path.GetRandomFileName, write name to files that have cryptographically-secure random names. This can enhance security or simplicity in the program.

advertisement
advertisement

The Path.GetRandomFileName method returns a random file name with an extension. This includes the period before the extension. The extension will be 1 dot and 3 letters, while the name will be 8 characters. The WriteRandomFile is called three times.

The WriteRandomFile method internally gets a random file name, gets the correct output path, and then writes some text to it. Using the random function print the strings randomly generated.

Runtime Test Cases
 
g4jgtjvbs7hbf
jtwoj782hggjsi
3jbws63k

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.