C# Code Snippets
Below are some useful C# code snippets for use in everyday projects.
Sometimes it may be necessary to accept input from the user so that it can be utilised within a script. This can be achieved using the 'ReadLine' method. Here, the input is placed into a variable called 'user' and then displayed as part of a greeting.
namespace DemoConsole { class Program { static void Main(string[] args) { // Greeting variable. string greeting = "Hello"; // Accept user input. Console.WriteLine("Please enter your name: "); string? user = Console.ReadLine(); // Display greeting. Console.WriteLine($"{greeting} {user}!"); } } }
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()); } } }
The 'Environment' class in the 'System' namespace can be used to access certain information relating to the computer that a program is running on. Below is an example of some of the information that is available.
Console.WriteLine($"Machine Name: {Environment.MachineName}"); Console.WriteLine($"Processor Count: {Environment.ProcessorCount}"); Console.WriteLine($"Operating System Version: {Environment.OSVersion}"); Console.WriteLine($"64-Bit Operating System: {Environment.Is64BitOperatingSystem}"); Console.WriteLine($"Username: {Environment.UserName}"); Console.WriteLine($"System Directory: {Environment.SystemDirectory}"); Console.WriteLine($"Current Directory: {Environment.CurrentDirectory}");
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); } } }
A delimited file can be processed line by line, and item by item within each line. The below example processes a CSV file, however, other delimiters would work in a similar way. For a tab delimited file, the tab escape character would need to be used, '\t'.
using System; using System.IO; namespace DemoConsole { class Program { static void Main(string[] args) { // File path. string filePath = @"C:\demo\people.csv"; // Assign the file to a reader object. using var reader = new StreamReader(filePath); // Data variables. string? line; string[] currentRow; // Process the contents of the reader object. while ((line = reader.ReadLine()) != null) { // Split the line at the delimiter. currentRow = line.Split(','); // Process the items in the row. foreach (string item in currentRow) { // Display the item in the console. Console.WriteLine(item); } // Blank line separator. Console.WriteLine(""); } } } }
A text file can be read from and processed line by line.
using System; using System.IO; namespace DemoConsole { class Program { static void Main(string[] args) { // Assign the text file to a reader object. using var reader = new StreamReader(@"C:\demo\demo.txt"); // Variable for a line of text from the file. string line = string.Empty; // Process the contents of the reader object. while ((line = reader.ReadLine()) != null) { // Display the line of text in the console. Console.WriteLine(line); } } } }
A regular expression can be used to remove control and other non-printable characters from a string as shown below.
using System; using System.Text.RegularExpressions; namespace DemoConsole { class Program { static void Main(string[] args) { string stringToClean = "String to clean: \u0000-\u0008\u000E-\u001F"; string cleanString = Regex.Replace(stringToClean, @"\p{C}+", string.Empty); } } }
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."); } } } } }