;

How to Generate Random Alpha Numeric String using GetRandomFileName method from the System.IO namespace in C#


Tutorialsrack 03/11/2019 C# Programs

In this article, we will learn how to generate random alphanumeric string using GetRandomFileName() method from the System.IO namespace in C#. Random String is sometimes needed. So we can generate a random alphanumeric string with a built-in method on the Path type. This method found under System.IO namespace, which generates random strings with high-quality randomness. This Method is short and allows you to quickly generate random strings with c# and can be used for random identifiers, codes, semi-secure passwords and anywhere else where you may require a random string to be used. It is easy to use.

This Path.GetRandomFileName method here is sometimes superior. Because it uses RNGCryptoServiceProvider for better randomness.

Here is the code to Generate Alphanumeric Random String using GetRandomFileName() method from the System.IO namespace in C#

Example - How to Generate Random Alpha Numeric String using GetRandomFileName method from the System.IO namespace in C#
using System;
using System.IO;

namespace Tutorialsrack
{
    class Program
    {
        /* How to Generate Random AlphaNumeric String using GetRandomFileName method from the System.IO namespace in C# */
        static void Main(string[] args)
        {
            Console.WriteLine("Random AlphaNumeric String is {0}", GenerateRandomAlphaNumericString());
            Console.WriteLine("Random AlphaNumeric String is {0}", GenerateRandomAlphaNumericString());
            Console.WriteLine("Random AlphaNumeric String is {0}", GenerateRandomAlphaNumericString());
            Console.WriteLine("Random AlphaNumeric String is {0}", GenerateRandomAlphaNumericString());
            Console.WriteLine("Random AlphaNumeric String is {0}", GenerateRandomAlphaNumericString());
            Console.ReadKey();
        }

        //Limitation of This method is 11 Characters String only
        public static string GenerateRandomAlphaNumericString()
        {
            string path = Path.GetRandomFileName();
            path = path.Replace(".", ""); // Remove period.
            return path;
        }

    }  
}

 

Output

Random AlphaNumeric String is qoc0qooisq0
Random AlphaNumeric String is wn3lbamty5q
Random AlphaNumeric String is u4w2jlu4y2h
Random AlphaNumeric String is ek5oe0ltyhf
Random AlphaNumeric String is vdf2rxvvasz

I hope this article will help you to understand how to generate Random alphanumeric string using GetRandomFileName() method from the System.IO namespace in C# in C#.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags