Convert String to Enum and Enum to string in C#

For example, we have the following enum: enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } Convert enum string Use Enum.ToString method To convert an enumeration value to String. Days days = Days.Monday; string stringEnum = days.ToString(); Console.Write(stringEnum); Convert string to enum string strString = "Monday"; Days days = (Days)Enum.Parse(typeof(Days), strString); Or to... » read more

Get List of Installed Windows Services using C#

Below is a program that will return all installed Windows Services on a local machine. The program uses the namespace System.ServiceProcess, which can be used by adding the Assemblies System.ServiceProcess.dll static void Main(string[] args) { System.ServiceProcess.ServiceController[] services = System.ServiceProcess.ServiceController.GetServices(); foreach (System.ServiceProcess.ServiceController service in services) { Console.WriteLine(service.ServiceName); } Console.ReadKey(); } Happy Coding! More C# Snippets

Create a new Thread Delegate using C#

Below is a code that demonstrates how to create a Thread Delegate, which calls a function that will do some work for you in the background. static void Main(string[] args) { // Creating a thread Delegate System.Threading.Thread _thread = new System.Threading.Thread(new System.Threading.ThreadStart(FuctionDoBackgroundWork)); _thread.Start(); } // Fucntion that the thread delegate Starts public static void FuctionDoBackgroundWork()... » read more

Get Hard Drive Type using C#

The snippet below will get you the drive type where a specified file/folder is. static void Main(string[] args) { System.IO.FileInfo file = new System.IO.FileInfo("M:\\"); // File or Directory System.IO.DriveInfo _driveInfo = new System.IO.DriveInfo(file.FullName); Console.WriteLine("Drive: " + _driveInfo.Name); if (_driveInfo.IsReady) { Console.WriteLine("The drive type is: " + _driveInfo.DriveType.ToString()); } Console.ReadLine(); } Output More C# Snippets

A function to Shuffle Array and List using C#

Below is a function that shuffles an array or a list. It accepts a list or array to be shuffled/rearranged as an argument and returns a shuffled copy of the object passed. public E ShuffleArrayAndList<E>(IList<E> arr) { Random random = new Random(); E result = arr[arr.Count]; E tmpArray = arr[arr.Count]; if (arr.Count > 1) {... » read more