2 Using Vanara.SystemServices
David Hall edited this page 2020-08-23 15:47:52 -06:00

Topics

Monitoring Registry Changes

// Create a new monitor instances with the key you wish to monitor
var monitor = new RegistryEventMonitor { RegistryKeyName = @"HKEY_CURRENT_USER\Software\Vanara", IncludeSubKeys = true };
// Setup event handlers for the changes you want to see
monitor.ValueChanged += (s, e) => { /* Perform your action here for when a value changes -- changed key name in 'e.RegistryKeyName' */ };
monitor.SubkeyChanged += (s, e) => { /* Perform your action here for when a subkey changes -- changed key in 'e.RegistryKeyName' */ };
// Start watching the specified registry key
monitor.EnableRaisingEvents = true;


// When you're done watching the registry...
monitor.EnableRaisingEvents = false;
monitor.Dispose();

Mapping to network folders

Trying to get the results of using WNetAddConnection2 or WNetEnumResource? Connecting to new remote folders or listing existing connections is easy with the NetworkDeviceConnection and NetworkDeviceConnectionCollection classes. These are accessible directly or through the Vanara.Computer class.

// Create a connection on the local machine: Same as 'net use \\MYSERVER\ShareName
var drvConn = NetworkDeviceConnection.Create(@"\\MYSERVER\ShareName");
// Create a connection with options: Same as 'net use X: \\MYSERVER\ShareName userpwd /USER:username /PERSISTENT:YES'
NetworkDeviceConnection.Create(@"\\MYSERVER\ShareName", "X:", "username", "userpwd", false, CONNECT.CONNECT_UPDATE_PROFILE);

// You can call those same methods from the Computer class
var mappedDrive = Computer.Local.NetworkDeviceConnections.Add(@"\\MYSERVER\ShareName", "*");
// Then remove it
Computer.Local.NetworkDeviceConnections.Remove(mappedDrive);

// The Computer class allows you connect using alternate creds
using var authLocal = new Computer(null, @"LOCALMACHINE\LocalUser", "password");
authLocal.NetworkDeviceConnections.Add(@"\\MYSERVER\ShareName");

// List all connections on the local computer using the current user
foreach (var conn in Computer.Local.NetworkDeviceConnections)
   Console.WriteLine($"{conn.LocalName}\t{conn.RemoteName}");

Creating shared folders

If you need to share out a folder on a machine, ala NetShareAdd or see what shared folders exist, ala NetShareEnum, you can use the SharedDevice and SharedDevices classes directly or via the Computer class.

// Create a shared folder on the local machine: Same as 'net share MyPicsShare=C:\Users\me\Pictures /REMARK:Some of my favorite pictures'
Computer.Local.SharedDevices.Add("MyPicsShare", "Some of my favorite pictures", @"C:\Users\me\Pictures");

// Create a share on another machine (assuming you have permission)
SharedDevice.Create("MYSERVER", "OtherPicShare", null, @"C:\Users\Other\Pictures");

// List all the shares on the local machine
foreach (var share in Computer.Local.SharedDevices.Values)
   Console.WriteLine($"{share.Name}={share.Path} ({share.Description})");