C# Code Snippets

Below are some useful C# code snippets for use in everyday projects.

When dealing with directories and files it may be necessary to check for their existence. Below is an example of how to do this.

using System;
using System.IO;

namespace DemoConsole
{
    class Program
    {

        static void Main(string[] args)
        {

            // Example path and file.
            string exampletPath = @"C:\demo\";
            string exampleFile = "example.txt";

            // Check if the path exists.
            if (Directory.Exists(exampletPath))
            {
                Console.WriteLine($"The path '{exampletPath}' exists.");
            }
            else
            {
                Console.WriteLine($"The path '{exampletPath}' doesn't exist.");
            }

            // Check if the file exists.
            if (File.Exists(Path.Combine(exampletPath, exampleFile)))
            {
                Console.WriteLine($"The file '{Path.Combine(exampletPath, exampleFile)}' exists.");
            }
            else
            {
                Console.WriteLine($"The file '{Path.Combine(exampletPath, exampleFile)}' doesn't exist.");
            }

        }

    }

}

Below is an example of how text can be converted to speech.

using System;
using System.Speech.Synthesis;

namespace DemoConsole
{
    class Program
    {

        static void Main(string[] args)
        {

            // Create an instance of the speech synthesizer.
            SpeechSynthesizer synthesizer = new SpeechSynthesizer();

            // Convert the text to speech.
            synthesizer.Speak("Hello World");

        }

    }

}

C# can be used to copy and move files.

using System;
using System.IO;

namespace DemoConsole
{
    class Program
    {

        static void Main(string[] args)
        {

            // Example paths and files.
            string exampletPathSource = @"C:\demo\";
            string exampletPathDestination = @"C:\demo\backup";
            string exampleFile1 = "example1.txt";
            string exampleFile2 = "example2.txt";

            // Copy the example1.txt file.
            File.Copy(Path.Combine(exampletPathSource, exampleFile1), 
                Path.Combine(exampletPathDestination, exampleFile1), true);

            // Move the example2.txt file.
            File.Move(Path.Combine(exampletPathSource, exampleFile2),
                Path.Combine(exampletPathDestination, exampleFile2), true);

        }

    }

}

Below is an example of how specific lines of content can be deleted from a file, by reading it line by line, whilst writing to a new file, omitting content as desired.

Here, lines of content are removed from an XML file, where they contain the opening section of an XML comment, '<!--'.

using System;
using System.IO;

namespace DemoConsole
{
    class Program
    {

        static void Main(string[] args)
        {

            // File variables.
            string inputFile = @"C:\Demo\Remove\personexport.xml";
            string outputFile = @"C:\Demo\Remove\personexport-no-comments.xml";

            // Text line variables.
            string textLine = null;
            string textLineDelete = "<!--";

            // StreamReader to read the XML file.
            using (StreamReader reader = new StreamReader(inputFile))
            {

                // StreamWriter to write to the new XML file.
                using (StreamWriter writer = new StreamWriter(outputFile))
                {

                    // Go through the lines of the XML file.
                    while ((textLine = reader.ReadLine()) != null)
                    {

                        // Write line to new file if it doesn't contain
                        // value in textLineDelete.
                        if (String.Compare(textLine, 
                            textLine.Replace(textLineDelete, "")) == 0)
                        {
                            writer.WriteLine(textLine);
                        }

                    }

                }

            }

        }

    }

}

Here is an example of how to generate a random number between two values, in this case 1 and 59, then display it.

using System;

namespace DemoConsole
{
    class Program
    {

        static void Main(string[] args)
        {

            //  Minimum and maximum values for random number.
            int minVal = 1;
            int maxVal = 59;

            // Generate random number.
            Random random = new Random();
            int randomNumber = random.Next(minVal, (maxVal + 1));

            // Display the result in the console.
            Console.WriteLine(randomNumber);

        }

    }

}

Here, a random password is generated from a specified set of characters. The length of the password is also randomly selected from a given minimum and maximum length.

using System;

namespace DemoConsole
{
    class Program
    {

        static void Main(string[] args)
        {

            // Possible characters in password.
            string alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string numbers = "0123456789";
            string nonAlpha = "{]+-[*=@:)}$^%;(_!&#?>/|.";

            // Combine possible password characters into character array.
            char[] charSet = (alpha + numbers + nonAlpha).ToCharArray();

            // Minimum and maximum password length.
            int minLength = 20;
            int maxLength = 30;

            // Create random instance.
            Random random = new Random();

            // Select a random password length between the minimum and maximum.
            int length = random.Next(minLength, (maxLength + 1));

            // Variable for new password.
            string result = "";

            // Construct new password.
            for (int i = 1; i <= length; i++)
            {

                // Add a randomly selected character to the new password.
                result += charSet[random.Next(0, ((charSet.Length-1) + 1))];

            }

            // Display the password.
            Console.WriteLine(result.ToString());

        }

    }

}

When handling a number of files, it can sometimes be useful to compress them in to one file. C# can be used to both create and extract from a zip archive.

using System;

namespace DemoConsole
{
    class Program
    {

        static void Main(string[] args)
        {

            // Example paths and files.
            string exampletPathSource = @"C:\demo\";
            string exampletPathDestination = @"C:\demo2\";
            string examplePathZip = @"C:\temp\demo.zip";

            // Create the zip archive file.
            ZipFile.CreateFromDirectory(exampletPathSource, examplePathZip);

            // Extract the zip archive file.
            ZipFile.ExtractToDirectory(examplePathZip, exampletPathDestination);

        }

    }

}

The code below takes input via the console and first checks whether a value has actually been entered. If a value has been entered, examples follow of how to check if it is a valid boolean, char, int, float and double. Where the value is valid for a specific data type, it is assigned to the respective variable using the 'out' keyword.

using System;

namespace DemoConsole
{
    class Program
    {

        static void Main(string[] args)
        {

            // Variables.
            bool boolExample;
            char charExample;
            int intExample;
            float floatExample;
            double doubleExample;

            // Output a message and take input from the user.
            Console.WriteLine("Please enter something: ");
            string inputAsString = Console.ReadLine();

            // Check if a value has been entered.
            if (string.IsNullOrEmpty(inputAsString))
            {
                Console.WriteLine("Nothing has been entered.");
            }
            else
            {

                // Assign the value to the variable boolExample
                // if it's a valid boolean.
                if (bool.TryParse(inputAsString, out boolExample))
                {
                    Console.WriteLine($"'{inputAsString}' is a valid boolean.");
                }
                else
                {
                    Console.WriteLine($"'{inputAsString}' is not a valid boolean.");
                }

                // Assign the value to the variable charExample
                // if it's a valid char.
                if (char.TryParse(inputAsString, out charExample))
                {
                    Console.WriteLine($"'{inputAsString}' is a valid char.");
                }
                else
                {
                    Console.WriteLine($"'{inputAsString}' is not a valid char.");
                }

                // Assign the value to the variable intExample
                // if it's a valid int.
                if (int.TryParse(inputAsString, out intExample))
                {
                    Console.WriteLine($"'{inputAsString}' is a valid int.");
                }
                else
                {
                    Console.WriteLine($"'{inputAsString}' is not a valid int.");
                }

                // Assign the value to the variable floatExample
                // if it's a valid float.
                if (float.TryParse(inputAsString, out floatExample))
                {
                    Console.WriteLine($"'{inputAsString}' is a valid float.");
                }
                else
                {
                    Console.WriteLine($"'{inputAsString}' is not a valid float.");
                }

                // Assign the value to the variable doubleExample
                // if it's a valid double.
                if (double.TryParse(inputAsString, out doubleExample))
                {
                    Console.WriteLine($"'{inputAsString}' is a valid double.");
                }
                else
                {
                    Console.WriteLine($"'{inputAsString}' is not a valid double.");
                }

            }

        }

    }

}