detect when a removable disk is inserted using C#

    	static ManagementEventWatcher w = null;
    	static void AddRemoveUSBHandler()
    	{
    		WqlEventQuery q;
    		ManagementScope scope = new ManagementScope("root\\CIMV2");
    		scope.Options.EnablePrivileges = true;
    		try {
    			q = new WqlEventQuery();
    			q.EventClassName = "__InstanceDeletionEvent";
    			q.WithinInterval = new TimeSpan(0, 0, 3);
    			q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
    			w = new ManagementEventWatcher(scope, q);
    			w.EventArrived += USBRemoved;
    			w.Start();
    		}
    		catch (Exception e) {
    			Console.WriteLine(e.Message);
    			if (w != null)
    			{
    				w.Stop();
    			}
    		}
    	}

    	static void AddInsertUSBHandler()
    	{
    		WqlEventQuery q;
    		ManagementScope scope = new ManagementScope("root\\CIMV2");
    		scope.Options.EnablePrivileges = true;
    		try {
    			q = new WqlEventQuery();
    			q.EventClassName = "__InstanceCreationEvent";
    			q.WithinInterval = new TimeSpan(0, 0, 3);
    			q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
    			w = new ManagementEventWatcher(scope, q);
    			w.EventArrived += USBInserted;
    			w.Start();
    		}
    		catch (Exception e) {
    			Console.WriteLine(e.Message);
    			if (w != null)
    			{
    				w.Stop();
    			}
    		}
    	}

    	static void USBInserted(object sender, EventArgs e)
    	{
    		Console.WriteLine("A USB device inserted");
    	}

    	static void USBRemoved(object sender, EventArgs e)
    	{
    		Console.WriteLine("A USB device removed");
    	}

How to use

    	Main()
    	{
    		AddInsertUSBHandler();
    		AddRemoveUSBHandler();
    		while (true) {}
    	}

http://stackoverflow.com/a/271251

Answer:WMI: Get USB device description on insertion

        ManagementScope sc =
            new ManagementScope(@"\\YOURCOMPUTERNAME\root\cimv2");

        ObjectQuery query =
            new ObjectQuery("Select * from Win32_USBHub");

        ManagementObjectSearcher searcher = new ManagementObjectSearcher(sc, query);
        ManagementObjectCollection result = searcher.Get();

        foreach (ManagementObject obj in result)
        {
            if (obj["Description"] != null) Console.WriteLine("Description:\t" + obj["Description"].ToString());
            if (obj["DeviceID"] != null) Console.WriteLine("DeviceID:\t" + obj["DeviceID"].ToString());
            if (obj["PNPDeviceID"] != null) Console.WriteLine("PNPDeviceID:\t" + obj["PNPDeviceID"].ToString());
        }

WMI Code creator : http://sdrv.ms/PZKlKu

http://stackoverflow.com/a/6643234
https://social.msdn.microsoft.com/Forums/vstudio/en-US/f3003f55-aecf-41da-b0a8-1b5e8bf99894/extracting-serial-number-vendor-id-and-product-id-from-usb-pendrive-using-c?forum=netfxbcl

Get different and common items in two arrays with LINQ [C#]

var list1 = new string[] {"1", "2", "3", "4", "5", "6"};
var list2 = new string[] {"2", "3", "4"};
var listCommon = list1.Intersect(list2);
foreach (string s in listCommon) Console.WriteLine(s);

Output:

2
3
4

 

http://stackoverflow.com/a/10648270

How to create a Winforms Combobox with Label and Value [C#]

    private void PopulateComboBox()
    {
        var dict = new Dictionary<int, string>();
        dict.Add(2324, "Toronto");
        dict.Add(64547, "Vancouver");
        dict.Add(42329, "Foobar");

        comboBox1.DataSource = new BindingSource(dict, null);
        comboBox1.DisplayMember = "Value";
        comboBox1.ValueMember = "Key";
    }

http://stackoverflow.com/a/2023457

Remove duplicates from array c#

int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();

http://stackoverflow.com/a/9685

Answer:Recommendations for a Hex Viewer Control for Windows.Forms?

There is a ByteViewer Control directly available in the .NET Framework. Here is how you can use it in a sample Winforms C# application (note: you need to reference the System.Design assembly):

Namespace: System.ComponentModel.Design
Assembly: System.Design (in System.Design.dll)

public Form1()
{
InitializeComponent();

ByteViewer bv = new ByteViewer();
bv.SetFile(@”c:\windows\notepad.exe”); // or SetBytes
Controls.Add(bv);
}


http://stackoverflow.com/a/23344431

Answer:How to edit a binary file’s hex value using C#

Position Value
——– ——
0 0x4D
1 0x5A
2 0x90
4 0x03
8 0x04
12 0xFF
13 0xFF
16 0xB8
24 0x40


using (var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite)) {
stream.Position = 24;
stream.WriteByte(0x04);
}

ref: http://stackoverflow.com/a/3217953?stw=2

Answer:Iterate two Lists or Arrays with one ForEach statement in C#

var numbers = new [] { 1, 2, 3, 4 };
var words = new [] { “one”, “two”, “three”, “four” };

var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });
foreach(var nw in numbersAndWords)
{
Console.WriteLine(nw.Number + nw.Word);
}

ref: http://stackoverflow.com/a/1955780?stw=2

convert seconds into (Hour:Minutes:Seconds:Milliseconds) / .NET

<= .NET 4.0

TimeSpan t = TimeSpan.FromSeconds( secs );
string answer = string.Format(“{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms”,
t.Hours,
t.Minutes,
t.Seconds,
t.Milliseconds);

NET > 4.0

TimeSpan time = TimeSpan.FromSeconds(seconds);
string str = time .ToString(@”hh\:mm\:ss\:fff”);

http://stackoverflow.com/a/463668

C# Splitting a string into chunks of a certain size (one-line)

List a = text.Select((c, i) => new { Char = c, Index = i }).GroupBy(o => o.Index / 4).Select(g => new String(g.Select(o => o.Char).ToArray())).ToList();

http://stackoverflow.com/a/1450808