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

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.

Free 30-Day Python Certification Bootcamp is Live. Join Now!
If you wish to look at all C# Programming examples, go to 1000 C# Programs.

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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.