TypesEdit

Floating-point numeric types (C# reference)[1]Edit

C# type/keyword Approximate range Precision Size .NET type
float ±1.5 x 10−45 to ±3.4 x 1038 ~6-9 digits 4 bytes System.Single
double ±5.0 × 10−324 to ±1.7 × 10308 ~15-17 digits 8 bytes System.Double
decimal ±1.0 x 10-28 to ±7.9228 x 1028 28-29 digits 16 bytes System.Decimal

Integral numeric types (C# reference)[2]Edit

C# type/keyword Range Size .NET type
sbyte -128 to 127 Signed 8-bit integer System.SByte
byte 0 to 255 Unsigned 8-bit integer System.Byte
short -32,768 to 32,767 Signed 16-bit integer System.Int16
ushort 0 to 65,535 Unsigned 16-bit integer System.UInt16
int -2,147,483,648 to 2,147,483,647 Signed 32-bit integer System.Int32
uint 0 to 4,294,967,295 Unsigned 32-bit integer System.UInt32
long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Signed 64-bit integer System.Int64
ulong 0 to 18,446,744,073,709,551,615 Unsigned 64-bit integer System.UInt64
nint Depends on platform (computed at runtime) Signed 32-bit or 64-bit integer System.IntPtr
nuint Depends on platform (computed at runtime) Unsigned 32-bit or 64-bit integer System.UIntPtr

Centre a form on the screen[3]Edit

this.CenterToScreen();

Make a winform control transparent[4]Edit

label1.BackColor = System.Drawing.Color.Transparent;

Make a winform draggable without a border[5][6]Edit

public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;

[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();

private void frmLicense_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        ReleaseCapture();
        SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
    }
}

Put this on the form, but rename frmLicense_ to suit your form name.

Add an event handler (form designer, select form, look at properties table, select the lightning bolt symbol, find the MouseDown event, select the method above from the combobox)

Random element from a listEdit

static Random rnd = new Random();
int r = rnd.Next(list.Count);
MessageBox.Show((string)list[r]);

Change startup form[7]Edit

Search solution for

Application.Run(new Form1());

In the program.cs file you will find the above line. Change the main function thus

static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new FORM_TO_RUN_ON_START());
    }

Split string on new line delimiter[8]Edit

string[] lines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None

Remove empty lines from stringEdit

private string RemoveEmptyLines(string lines)
    {
        return Regex.Replace(lines, @"^\s*$\n|\r", "\r", RegexOptions.Multiline).TrimEnd();
    }

Declare array of length[9]Edit

string[] a = new string[5];

Share variables between classes[10]Edit

Create a static class in the code:

public static class sharedStrings
{
    public static string aSharedString { get; set; }
}

Then it can be get or set from any namespace at runtime:

public static void someFunctionInADifferentClass()
{
    sharedStrings.aSharedString = "test string";
}

Console applications argsEdit

static void Main(string[] args)
    {
        // Display the number of command line arguments.
        Console.WriteLine(args.Length);
        // Retrieve the first argument
        string first = args[0];
    }

Disable nullable warningsEdit

Put this on the first line:

#nullable disable

ComboboxEdit

This copies the items from one combobox to another[11].

comboBox2.Items.AddRange(comboBox1.Items.Cast<Object>().ToArray());

List declarationEdit

List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");

or a one-liner:

var list = new List<string> { "One", "Two", "Three" };

Wait / promptEdit

// Wait/prompt
static void wp()
{
    Console.WriteLine("Press a key to continue."); Console.ReadKey();                           // wait for a keypress
}

File encryption (aes)Edit

 using System.Security.Cryptography;
 public class EncDec
    {
        // entry point
        static void Main()
        {
            Console.WriteLine("Enter to start"); Console.ReadLine();                                    // start
            Aes alg = EncryptFile(@"c:\temp\2", @"c:\temp\2.enc");                                      // encrypt file (the aes is returned)
            Console.WriteLine("Key:");                                                                  // show key
            foreach (var item in alg.Key)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("IV:");
            foreach (var item in alg.IV)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
            Decrypt(@"c:\temp\2.enc", @"c:\temp\2.dec", alg);                                           // decrypt file (using provided aes)
            Console.WriteLine("Done"); Console.ReadLine();
        }

        // Encrypt a file into another file using a password 
        public static Aes EncryptFile(string fileIn, string fileOut)
        {
            FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read);                   // open the file streams 
            FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
            Aes alg = Aes.Create();                                                                     // create the aes object
            CryptoStream cs = new CryptoStream(fsOut, alg.CreateEncryptor(), CryptoStreamMode.Write);   // create a crypto stream
            int bufferLen = 4096;                                                                       // initialize a buffer
            byte[] buffer = new byte[bufferLen];
            int bytesRead;
            do
            {
                bytesRead = fsIn.Read(buffer, 0, bufferLen);                                            // read a chunk of data from the input file
                cs.Write(buffer, 0, bytesRead);                                                         // encrypt it
            } while (bytesRead != 0);
            cs.Close();                                                                                 // close everything
            fsIn.Close();
            return alg;                                                                                 // return the used aes key for storing
        }

        // Decrypt a file into another file using a password 
        public static void Decrypt(string fileIn, string fileOut, Aes algg)
        {
            FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read);                   // open the file streams
            FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
            Aes alg = Aes.Create();                                                                     // create the aes object
            alg.Key = algg.Key;                                                                         // extract key from the provided aes
            alg.IV = algg.IV;                                                                           // extract the IV from the provided aes
            CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(), CryptoStreamMode.Write);   // create a crypto stream
            int bufferLen = 4096;                                                                       // initialize a buffer
            byte[] buffer = new byte[bufferLen];
            int bytesRead;
            do
            {
                bytesRead = fsIn.Read(buffer, 0, bufferLen);                                            // read a chunk of data from the input file
                cs.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);                                                                   // Decrypt it 
            cs.Close();                                                                                 // close everything 
            fsIn.Close();
        }

File compression (lz4)[12]Edit

using K4os.Compression.LZ4.Streams;
public class lzh
{
    static void Main()
    {
        CompressFile(@"c:\temp\2021-08-22 13-26-40.flv", @"c:\temp\2021-08-22 13-26-40.flv.lz4");
        DecompressFile(@"c:\temp\2021-08-22 13-26-40.flv.lz4", @"c:\temp\2021-08-22 13-26-40.flv.lz4.flv");
    }

    // Compress a file to disk
    static void CompressFile(string sourcefn, string destinationfn)
    {
        using (var source = File.OpenRead(sourcefn))
        using (var target = LZ4Stream.Encode(File.Create(destinationfn)))
        {
            source.CopyTo(target);
        }
    }

    // Decompress a file to disk
    static void DecompressFile(string sourcefn, string destinationfn)
    {
        using (var source = LZ4Stream.Decode(File.OpenRead(sourcefn)))
        using (var target = File.Create(destinationfn))
        {
            source.CopyTo(target);
        }
    }

File toolsEdit

static long GetDirectorySize(string folderPath)
{
    DirectoryInfo di = new DirectoryInfo(folderPath);
    return di.EnumerateFiles("*", SearchOption.AllDirectories).Sum(fi => fi.Length);
}

static long GetFileSize(string filePath)
{
    FileInfo di = new FileInfo(filePath);
    return di.Length;
}

(string FullName, string Name, string Extension, string DirectoryName, long Length, FileAttributes Attributes, bool IsReadOnly, DateTime CreationTime, DateTime LastWriteTime, DateTime LastAccessTime) GetFileInfo(string filePath)
{
    using FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
    FileInfo di = new FileInfo(filePath);
    FileAttributes b = di.Attributes;
    Console.WriteLine((double)b);
    return (di.FullName, di.Name, di.Extension, di.DirectoryName, di.Length, di.Attributes, di.IsReadOnly, di.CreationTime, di.LastWriteTime, di.LastAccessTime);
}

SpinnersEdit

namespace testing_stuff
{
    using System;
    using System.Threading;

    public class Example
    {
        // <<-------- Main thread --------------------------------
        private static void Main()
        {
            spinner(1, false);
            Main();
        }
        // ----------------------------------------------------->>

        static void spinner(int spin, bool bd)
        {
            Console.OutputEncoding = System.Text.Encoding.Unicode;
            string[] spinners = {
                "▌▀▐▄",
                "┤┘┴└├┌┬┐",
                "|/-\\",
                ".oO@*"
            };
            int c = spinners[spin].Length;
            for (int i = 0; i < c; i++)
            {
                char ch = (spinners[spin])[i];
                Console.Clear();
                Console.Write(ch.ToString());
                Thread.Sleep(250);
            }
        }
    }
}

File lockEdit

This locks a file in another thread where the other thread could perform multiple operations on the file while it is locked. This is not very useful.

using System.Text;
class Program
{
    static void Main()
    {
        lockk(@"c:\temp\2");
    }

    static void lockk(string fn)
    {
        var ts = new CancellationTokenSource();
        CancellationToken ct = ts.Token;
        Task.Factory.StartNew(() =>
            {
                FileStream fs = new FileStream(fn, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
                Console.WriteLine("Locked");
                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        fs.Close();
                        fs.Dispose();
                        break;
                    }
                }
            }, ct);

        Console.ReadLine();
        ts.Cancel();
        Console.WriteLine("Unlocked");
        Console.ReadLine();
    }
}

Console thread launch a simple threadEdit

Launches a new thread in a very simple way.

using System.Threading;
new Thread(() =>
{
    Thread.CurrentThread.IsBackground = true;
    /* run your code here */
    Console.WriteLine("Hello, world");
}).Start();

Console menu template with threaded animations and thread start and stop operationsEdit

using System.Data;

namespace Limbo_fs
{
    internal class Program
    {
        #region"main and console options list"

        // main program entry point
        static void Main()
        {
            ConsoleKeyInfo cki;
            Console.TreatControlCAsInput = false;                                   // Prevent example from ending if CTL+C is pressed.
            WriteConsoleOptions();                                                  // display the available options
            do
            {
                cki = Console.ReadKey();                                            // get the keypress
                if ((cki.Modifiers & ConsoleModifiers.Alt) !=
                    0) Console.Write("ALT+");                                       //}
                if ((cki.Modifiers & ConsoleModifiers.Shift) !=
                    0) Console.Write("SHIFT+");                                     //} capture control characters
                if ((cki.Modifiers & ConsoleModifiers.Control) !=
                    0) Console.Write("CTL+");                                       //}
                switch (cki.KeyChar.ToString())                                     //}
                {
                    case "1":                                                       //}
                        Console.Clear();
                        YouPressed1("Create Storage Resource");                     //} launch it and give it a name
                        Thread.Sleep(500);                                          //}
                        break;                                                      //}
                    case "2":                                                       //}
                        Console.Clear();
                        YouPressed2("Pointless Loop");                              //} launch it and give it a name
                        Thread.Sleep(500);                                          //}
                        break;                                                      //} 
                    case "3":                                                       //} select the keypress and act accordingly
                        // call something                                           //}
                        Thread.Sleep(500);                                          //}
                        break;                                                      //} 
                    case "q":                                                       //} 
                        Quit();                                                     //}
                        break;                                                      //} 
                    default:                                                        //} 
                        break;                                                      //} 
                }
                WriteConsoleOptions();                                              // write out the options again after action
            } while (true);
        }

        // method to write out options
        static void WriteConsoleOptions()
        {
            Console.Clear();                                                        // clear console
            Console.WriteLine("Choose an Option\n");                                //}
            Console.WriteLine("1 \t Create Storage Resource");                      //}
            Console.WriteLine("2 \t Option 2");                                     //} write out the options
            Console.WriteLine("3 \t Option 3");                                     //}
            Console.WriteLine();
            Console.WriteLine("Q \t Quit\n");                                       //}
            var originalX = Console.CursorLeft;                                     //}
            var originalY = Console.CursorTop;                                      //}
            var y = Console.WindowHeight - 2;                                       //}
            var w = Console.WindowWidth;                                            //} draw the animation and the bottom status bar
            Console.SetCursorPosition(0, y);                                        //} 
            for (int j = 0; j < w; j++)                                             //}
            {                                                                       //}
                Console.Write("-");                                                 //}
            }                                                                       //}
            Console.Write("Main Menu");                                             //}
            Console.SetCursorPosition(originalX, originalY);                        //}
            Thread.Sleep(100);                                                      //}
        }

        // method for quit
        static void Quit()
        {
            Console.Clear();
            var h = Console.WindowHeight;
            var w = Console.WindowWidth;
            string GoodbyeMessage = @"'Thank you, come again' (Apu, Simpsons)";
            int n = GoodbyeMessage.Length;
            Console.SetCursorPosition(w / 2 - n / 2, h / 2);
            Console.WriteLine(GoodbyeMessage);
            Thread.Sleep(1000);
            Environment.Exit(0);                                                    // quit app
        }
        #endregion

        #region"animation task"
        // <<--------- animation task --------------------------
        static void BusyAnimation(bool onOff, string tn, CancellationToken ct)
        {
            if (ct.IsCancellationRequested)                                         //}
            {                                                                       //}
                ct.ThrowIfCancellationRequested();                                  //} handle multiple cancels
            }                                                                       //}
            string[] BusySymbols = new[] { "|", "/", "-", "\\" };
            var originalX = Console.CursorLeft;                                     //}
            var originalY = Console.CursorTop;                                      //}
            var y = Console.WindowHeight - 2;                                       //}
            var w = Console.WindowWidth;                                            //} draw the animation and the bottom status bar
            Console.SetCursorPosition(0, y);                                        //} 
            for (int j = 0; j < w; j++)                                             //}
            {                                                                       //}
                Console.Write("-");                                                 //}
            }                                                                       //}
            Console.Write("Working in menu: " + tn);                                //} animation can be on or off
            Console.SetCursorPosition(originalX, originalY);                        //}
            do                                                                      //}
            {                                                                       //}
                if (onOff)
                {
                    for (int i = 0; i < BusySymbols.Length; i++)                    //} 
                    {                                                               //}
                        originalX = Console.CursorLeft;                             //}
                        originalY = Console.CursorTop;                              //}
                        y = Console.WindowHeight - 2;                               //}
                        Console.SetCursorPosition(0, y);                            //} 
                        for (int j = 0; j < w; j++)                                 //}
                        {                                                           //}
                            Console.Write("-");                                     //}
                        }                                                           //}
                        Console.Write((onOff ? BusySymbols[i] + " " : "") +         //} animation can be on or off
                        "Executing task: " + tn);                                   //} animation can be on or off
                        Console.SetCursorPosition(originalX, originalY);            //}
                        Thread.Sleep(100);                                          //}
                    }
                }

            } while (!ct.IsCancellationRequested);                                  //} process the cancel
        }
        // ----------------------------------------------------->>
        #endregion

        // method on option 1
        static void YouPressed1(string tName)
        {
            var tokenSource = new CancellationTokenSource();                        // setup the token source
            var token = tokenSource.Token;                                          // setup the token
            Task t;                                                                 // create the animation task
            t = Task.Run(() => BusyAnimation(false, tName, token), token);          // start the animation - true or false toggles the spinner

            // <-------- useful work
            Console.WriteLine("Enter location");
            string inp = Console.ReadLine();
            Console.WriteLine("Enter size in bytes");
            string a = Console.ReadLine();
            Console.WriteLine("you entered location: " + inp + " size: " + a);
            Console.WriteLine("\nPress a key to return...");
            Console.ReadLine();
            // useful work -------->

            tokenSource.Cancel();                                                   // cancel the animation
            tokenSource.Dispose();                                                  // dispose the animation
        }

        static void YouPressed2(string tName)
        {
            var tokenSource = new CancellationTokenSource();                        // setup the token source
            var token = tokenSource.Token;                                          // setup the token
            Task t;                                                                 // create the animation task
            t = Task.Run(() => BusyAnimation(true, tName, token), token);           // start the animation - true or false toggles the spinner

            // <-------- useful work
            for (int i = 0; i < 20; i++)
            {
                Console.WriteLine("Enter location");
                Thread.Sleep(200);
            }
            // useful work -------->

            tokenSource.Cancel();                                                   // cancel the animation
            tokenSource.Dispose();                                                  // dispose the animation
        }
    }
}

Helper functionsEdit

// get location of thie running application
static string GetSelfPath()
{
    string b = System.Reflection.Assembly.GetExecutingAssembly().Location;
    if (b != null)
    {
        return b;
    }
    else { return ""; }
}

// get directory from a full path
static string GetDirectoryName(string fullpath)
{
    string b = Path.GetDirectoryName(fullpath)!;                                     // return the directory part of the path
    if (b != null)
    {
        return b;
    }
    else { return ""; }
}

// get filename from a full path
static string GetFileName(string fullpath)
{
    return Path.GetFileName(fullpath);                                              // return the filename of the path
}
    // delete file
static void DeleteFile(string fullpath)
{
    System.IO.File.Delete(fullpath);                                                // delete the file
}

// is file locked function - returns true if locked
protected virtual bool IsFileLocked(FileInfo file)
{
    try
    {
        using FileStream stream = file.Open                                        // the file is unavailable because it is:
            (FileMode.Open,                                                         // still being written to
            FileAccess.Read,                                                        // or being processed by another thread
            FileShare.None);                                                        // or does not exist
        stream.Close();
    }
    catch (IOException)
    {
        return true;
    }
    //file is not locked
    return false;
}

// write a string to file
static void WriteStringContentsToFile(string contents, string filename)
{
    string[] line = contents.Split('\n');
    int count = line.Length;
    try
    {
        using StreamWriter writer = new(filename);                                  // Write file using StreamWriter
        for (int i = 0; i < count; i++)
            writer.WriteLine(line[i]);                                              // loop through the string
    }
    catch { MessageBox.Show("Couldn't write the file"); }
}

// reads in a file and returns a string of it
static string ReadInFile(string fileName)
{
    string b = "";                                                                  // container for the string
    try
    {
        string[] a = System.IO.File.ReadAllLines(fileName);                         // open the logfile into a string array
        foreach (string line in a)                                                  //}
        {                                                                           //} loop through the lines
            b += (line + Environment.NewLine);                                      //} and create a string
        }                                                                           //}
    }
    catch { MessageBox.Show("Couldn't read the file"); }
    return b;                                                                       // return the string
}

Enumeration (e.g. for use in Class definitions)[13]Edit

public enum Direction 
{
    Up,
    Down,
    Left,
    Right
}

Console FileSystemWatcher[14]Edit

using System.Collections.Concurrent;
using System.IO;

public class FileChangeProcessor
{
    private FileSystemWatcher watcher;
    private BlockingCollection<string> queue;
    private ConcurrentDictionary<string, DateTime> processedFileMap;
    public FileChangeProcessor()
    {
        watcher = new FileSystemWatcher(@"C:\temp\", filter: @"*.txt");
        queue = new BlockingCollection<string>();
        processedFileMap = new ConcurrentDictionary<string, DateTime>();

        watcher.Changed += (_, e) => queue.Add(e.FullPath);
        watcher.Created += (_, e) => queue.Add(e.FullPath);
    }

    public void StartProcessingFileChanges()
    {
        //Start watcher
        watcher.EnableRaisingEvents = true;

        //Start consuming queue
        while (!queue.IsCompleted)
        {
            var filePath = queue.Take(); //Blocking dequeue
            var fileInfo = new FileInfo(filePath);

            if (!fileInfo.Exists)
                continue;

            if (processedFileMap.TryGetValue(filePath, out DateTime processedWithModDate))
            {
                if (processedWithModDate == fileInfo.LastWriteTimeUtc)
                {
                    Console.WriteLine($"Ignoring duplicate change event for file: {filePath}");
                    continue;
                }

                //It's a new change, so process it, then update mod date.
                Console.WriteLine($"Processed file again: {filePath}");
                processedFileMap[filePath] = fileInfo.LastWriteTimeUtc;
            }
            else
            {
                //We haven't processed this file before. Process it, then save the mod date.
                Console.WriteLine($"Processed file for the first time: {filePath}.");
                processedFileMap.TryAdd(filePath, fileInfo.LastWriteTimeUtc);
            }
        }
    }
}

Using it:

var fileChangeProcessor = new FileChangeProcessor();
Task.Run(() => fileChangeProcessor.StartMonitoringChanges());

Console.WriteLine("Creating file");
File.WriteAllText(@"C:\temp\movies.txt", "hello");
Console.ReadLine();

Console.WriteLine("Updating file");
File.WriteAllText(@"C:\temp\movies.txt", "hello world");
Console.ReadLine();

Typical output:

Creating file
Processed file for the first time: C:\temp\movies.txt.
Ignoring duplicate change event for file: C:\temp\movies.txt

Updating file
Processed file again: C:\temp\movies.txt
Ignoring duplicate change event for file: C:\temp\movies.txt

Time (ntp)[15]Edit

        // Gets time in UTC from an NTP server and returns it or the epoch date if it can't connect
        public static DateTime GetNetworkTime()
        {
            string ntpServer = "";
            var ntpData = new byte[48];
            ntpData[0] = 0x1B;
            IPAddress[] addresses;
            try                                                                                     // try a trusty ntp server
            {
                ntpServer = "pool.ntp.org";
                addresses = Dns.GetHostEntry(ntpServer).AddressList;
            }
            catch { }                                                                               // but if the trusty fails, try another
            {
                List<string> ts = new List<string> {
                "0.amazon.pool.ntp.org",
"0.android.pool.ntp.org",
"0.arch.pool.ntp.org",
"0.asia.pool.ntp.org",
"0.askozia.pool.ntp.org",
"0.centos.pool.ntp.org",
"0.debian.pool.ntp.org",
"0.dragonfly.pool.ntp.org",
"0.europe.pool.ntp.org",
"0.fedora.pool.ntp.org",
"0.freebsd.pool.ntp.org",
"0.gentoo.pool.ntp.org",
"0.netbsd.pool.ntp.org",
"0.north-america.pool.ntp.org",
"0.openbsd.pool.ntp.org",
"0.opensuse.pool.ntp.org",
"0.opnsense.pool.ntp.org",
"0.pfsense.pool.ntp.org",
"0.pool.ntp.org",
"0.ru.pool.ntp.org",
"0.smartos.pool.ntp.org",
"1.amazon.pool.ntp.org",
"1.android.pool.ntp.org",
"1.arch.pool.ntp.org",
"1.asia.pool.ntp.org",
"1.askozia.pool.ntp.org",
"1.centos.pool.ntp.org",
"1.debian.pool.ntp.org",
"1.dragonfly.pool.ntp.org",
"1.europe.pool.ntp.org",
"1.fedora.pool.ntp.org",
"1.freebsd.pool.ntp.org",
"1.gentoo.pool.ntp.org",
"1.netbsd.pool.ntp.org",
"1.north-america.pool.ntp.org",
"1.openbsd.pool.ntp.org",
"1.opensuse.pool.ntp.org",
"1.opnsense.pool.ntp.org",
"1.pfsense.pool.ntp.org",
"1.pool.ntp.org",
"1.ru.pool.ntp.org",
"1.smartos.pool.ntp.org",
"2.amazon.pool.ntp.org",
"2.android.pool.ntp.org",
"2.arch.pool.ntp.org",
"2.asia.pool.ntp.org",
"2.askozia.pool.ntp.org",
"2.centos.pool.ntp.org",
"2.debian.pool.ntp.org",
"2.dragonfly.pool.ntp.org",
"2.europe.pool.ntp.org",
"2.fedora.pool.ntp.org",
"2.freebsd.pool.ntp.org",
"2.gentoo.pool.ntp.org",
"2.netbsd.pool.ntp.org",
"2.north-america.pool.ntp.org",
"2.openbsd.pool.ntp.org",
"2.opensuse.pool.ntp.org",
"2.opnsense.pool.ntp.org",
"2.pfsense.pool.ntp.org",
"2.pool.ntp.org",
"2.ru.pool.ntp.org",
"2.smartos.pool.ntp.org",
"3.amazon.pool.ntp.org",
"3.android.pool.ntp.org",
"3.arch.pool.ntp.org",
"3.asia.pool.ntp.org",
"3.askozia.pool.ntp.org",
"3.centos.pool.ntp.org",
"3.debian.pool.ntp.org",
"3.dragonfly.pool.ntp.org",
"3.europe.pool.ntp.org",
"3.fedora.pool.ntp.org",
"3.freebsd.pool.ntp.org",
"3.gentoo.pool.ntp.org",
"3.netbsd.pool.ntp.org",
"3.north-america.pool.ntp.org",
"3.openbsd.pool.ntp.org",
"3.opensuse.pool.ntp.org",
"3.opnsense.pool.ntp.org",
"3.pfsense.pool.ntp.org",
"3.pool.ntp.org",
"3.ru.pool.ntp.org",
"3.smartos.pool.ntp.org",
"asia.pool.ntp.org",
"bonehed.lcs.mit.edu",
"chime1.surfnet.nl",
"clock.nyc.he.net",
"clock.sjc.he.net",
"clock.uregina.ca",
"cronos.cenam.mx",
"europe.pool.ntp.org",
"gbg1.ntp.se",
"gbg2.ntp.se",
"gnomon.cc.columbia.edu",
"gps.layer42.net",
"hora.roa.es",
"level1e.cs.unc.edu",
"minuto.roa.es",
"mizbeaver.udel.edu",
"mmo1.ntp.se",
"mmo2.ntp.se",
"navobs1.gatech.edu",
"navobs1.oar.net",
"navobs1.wustl.edu",
"north-america.pool.ntp.org",
"now.okstate.edu",
"ntp.dianacht.de",
"ntp.fiord.ru",
"ntp.fizyka.umk.pl",
"ntp.gsu.edu",
"ntp.i2t.ehu.eus",
"ntp.ix.ru",
"ntp.lcf.mx",
"ntp.mrow.org",
"ntp.nat.ms",
"ntp.neel.ch",
"ntp.neu.edu.cn",
"ntp.nic.cz",
"ntp.nict.jp",
"ntp.nict.jp",
"ntp.nsu.ru",
"ntp.ntsc.ac.cn",
"ntp.psn.ru",
"ntp.qix.ca",
"ntp.quintex.com",
"ntp.ripe.net",
"ntp.rsu.edu.ru",
"ntp.se",
"ntp.shoa.cl",
"ntp.sstf.nsk.ru",
"ntp.time.in.ua",
"ntp.vsl.nl",
"ntp.your.org",
"ntp.yycix.ca",
"ntp0.as34288.net",
"ntp0.nl.uu.net",
"ntp0.ntp-servers.net",
"ntp1.as34288.net",
"ntp1.fau.de",
"ntp1.hetzner.de",
"ntp1.inrim.it",
"ntp1.jst.mfeed.ad.jp",
"ntp1.net.berkeley.edu",
"ntp1.niiftri.irkutsk.ru",
"ntp1.nl.uu.net",
"ntp1.ntp-servers.net",
"ntp1.oma.be",
"ntp1.qix.ca",
"ntp1.stratum1.ru",
"ntp1.usv.ro",
"ntp1.vniiftri.ru",
"ntp2.fau.de",
"ntp2.hetzner.de",
"ntp2.inrim.it",
"ntp2.jst.mfeed.ad.jp",
"ntp2.net.berkeley.edu",
"ntp2.niiftri.irkutsk.ru",
"ntp2.ntp-servers.net",
"ntp2.oma.be",
"ntp2.qix.ca",
"ntp2.stratum1.ru",
"ntp2.stratum2.ru",
"ntp2.time.in.ua",
"ntp2.usno.navy.mil",
"ntp2.vniiftri.ru",
"ntp21.vniiftri.ru",
"ntp3.hetzner.de",
"ntp3.jst.mfeed.ad.jp",
"ntp3.ntp-servers.net",
"ntp3.stratum1.ru",
"ntp3.stratum2.ru",
"ntp3.time.in.ua",
"ntp3.usv.ro",
"ntp3.vniiftri.ru",
"ntp4.ntp-servers.net",
"ntp4.stratum1.ru",
"ntp4.stratum2.ru",
"ntp4.vniiftri.ru",
"ntp5.ntp-servers.net",
"ntp5.stratum1.ru",
"ntp5.stratum2.ru",
"ntp6.ntp-servers.net",
"ntp7.ntp-servers.net",
"ntp-galway.hea.net",
"ntps1.pads.ufrj.br",
"ntps1-0.cs.tu-berlin.de",
"ntps1-0.uni-erlangen.de",
"ntps1-1.cs.tu-berlin.de",
"ntps1-1.uni-erlangen.de",
"otc1.psu.edu",
"pool.ntp.org",
"ptbtime1.ptb.de",
"ptbtime2.ptb.de",
"rackety.udel.edu",
"ru.pool.ntp.org",
"rustime01.rus.uni-stuttgart.de",
"rustime02.rus.uni-stuttgart.de",
"sth1.ntp.se",
"sth2.ntp.se",
"stratum1.net",
"svl1.ntp.se",
"svl2.ntp.se",
"t2.timegps.net",
"tempus1.gum.gov.pl",
"tempus2.gum.gov.pl",
"tick.ucla.edu",
"tick.uh.edu",
"tick.usask.ca",
"tick.usno.navy.mil",
"time.apple.com",
"time.cloudflare.com",
"time.esa.int",
"time.euro.apple.com",
"time.facebook.com",
"time.fu-berlin.de",
"time.google.com",
"time.nist.gov",
"time.nrc.ca",
"time.ufe.cz",
"time.windows.com",
"time1.esa.int",
"time1.facebook.com",
"time1.google.com",
"time1.stupi.se",
"time2.facebook.com",
"time2.google.com",
"time3.facebook.com",
"time3.google.com",
"time4.facebook.com",
"time4.google.com",
"time5.facebook.com",
"time-a.as43289.net",
"time-a-b.nist.gov",
"time-a-g.nist.gov",
"time-a-wwv.nist.gov",
"time-b.as43289.net",
"time-b-b.nist.gov",
"time-b-g.nist.gov",
"time-b-wwv.nist.gov",
"time-c.as43289.net",
"time-c-b.nist.gov",
"time-c-g.nist.gov",
"time-c-wwv.nist.gov",
"time-d-b.nist.gov",
"time-d-g.nist.gov",
"time-d-wwv.nist.gov",
"time-e-b.nist.gov",
"time-e-g.nist.gov",
"time-e-wwv.nist.gov",
"timehost.lysator.liu.se",
"timekeeper.isi.edu",
"tock.usask.ca",
"tock.usno.navy.mil",
"tock.usshc.com",
"ts1.aco.net",
"ts2.aco.net",
"utcnist.colorado.edu",
"utcnist.colorado.edu",
"utcnist2.colorado.edu",
"utcnist2.colorado.edu",
"vniiftri.khv.ru",
"vniiftri2.khv.ru",
"x.ns.gin.ntt.net",
"y.ns.gin.ntt.net",
"zeit.fu-berlin.de",

};
                Random rnd = new Random();
                int r = rnd.Next(ts.Count);
                ntpServer = ts[r];
                addresses = Dns.GetHostEntry(ntpServer).AddressList;
            }
            var ipEndPoint = new IPEndPoint(addresses[0], 123);
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.ReceiveTimeout = 3000;                                                           // introduce a timeout in case of socket error
            socket.Connect(ipEndPoint);
            socket.Send(ntpData);
            try { socket.Receive(ntpData); }
            catch {
                DateTime epoch = DateTime.MinValue;                                                 // in case of error, return the epoch date
                return epoch; }
            socket.Close();
            ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | (ulong)ntpData[43];
            ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | (ulong)ntpData[47];
            var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
            var networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);
            return networkDateTime;
        }

ReferencesEdit

  1. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types
  2. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types
  3. https://stackoverflow.com/questions/4601827/how-do-i-center-a-window-on-the-screen-in-c-sharp-winforms
  4. https://stackoverflow.com/questions/4639482/how-to-do-a-background-for-a-label-will-be-without-color
  5. https://www.reddit.com/r/csharp/comments/do7pu6/how_do_you_add_event_handlers_to_a_designer_file/
  6. https://stackoverflow.com/questions/23966253/moving-form-without-title-bar
  7. https://stackoverflow.com/questions/1650562/how-do-i-change-what-form-loads-on-startup
  8. https://stackoverflow.com/questions/1814562/how-to-split-strings-on-carriage-return-with-c#:~:text=%5B%5D%20result%20%3D%20test.-,Split(new%20string%5B%5D%20%7B%22%5Cn%22%2C%20%22,PersonB%22%20and%20%22PersonC%22.
  9. https://stackoverflow.com/questions/18074925/vb-net-how-to-declare-new-empty-array-of-known-length
  10. https://stackoverflow.com/questions/45441063/c-sharp-share-or-modify-variables-between-classes
  11. https://stackoverflow.com/questions/39901191/duplicate-items-from-one-combobox-to-another-in-one-step
  12. https://github.com/MiloszKrajewski/K4os.Compression.LZ4
  13. https://stackoverflow.com/questions/45510967/fixed-values-for-property-c-sharp
  14. https://makolyte.com/event-driven-dotnet-use-filesystemwatcher-instead-of-polling-for-new-files/
  15. https://stackoverflow.com/questions/1193955/how-to-query-an-ntp-server-using-c