How do I remove the keys from Local machine\SOFTWARE? - c#

I tried to delete a test key through a C# script. The following code is my script, I also added admin value in manifest file for this project UAC. But it still doesn't work. Even restarted Visual Studio 2017 with Admin mode.
The error message said Cannot write to the registry key.
Not sure what's wrong in the script.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.Security;
using System.Security.AccessControl;
using System.Security.Principal;
namespace temp_code_tester
{
class Program
{
static void Main(string[] args)
{
//Get current login account info from another Class
//string userName = WindowsIdentity.GetCurrent().Name;
//var SecCheck = new SecutriyProcesser();
//SecCheck.AddRule(userName);
var RunCheck = new AccessRegistry();
RunCheck.ACL("Test");
}
}
class AccessRegistry
{
public void ACL(string name)
{
Console.WriteLine("Getting the registry keys.....");
Console.WriteLine("---------------------------------------------\n");
//Open the SOFTWARE keys and input those keys into array
RegistryKey SoftKey = Registry.LocalMachine.OpenSubKey(#"SOFTWARE");
string[] lists = SoftKey.GetSubKeyNames();
foreach (string KeyName in lists)
{
Console.WriteLine(KeyName);
}
foreach (string value in lists)
{
if (value.Contains(name)) // if we find the key, then lists all subkeys
{
//Registry.LocalMachine.DeleteSubKeyTree(value);
Console.WriteLine("\nMatch one: {0}", value);
var RightKey = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\" + value);
string[] SubList = RightKey.GetSubKeyNames();
foreach (string SubValue in SubList)
{
Console.WriteLine("Folder: {0} is under this key", SubValue);
}
if (SubList.Length > 1)
{
try
{
SoftKey.DeleteSubKeyTree(value);
Console.WriteLine("\nThe folder {0} has been removed", value);
}
catch (Exception er)
{
Console.WriteLine("Error: {0}", er.Message);
}
}
else
{
try
{
SoftKey.DeleteSubKey(value);
}
catch (Exception)
{
throw;
}
}
}
}
SoftKey.Close();
}
}
class SecutriyProcesser
{
// A method about add enough roles for current window account
public void AddRule(string userName)
{
RegistrySecurity rs = new RegistrySecurity();
rs.AddAccessRule(new RegistryAccessRule(userName,
RegistryRights.FullControl,
InheritanceFlags.ObjectInherit,
PropagationFlags.InheritOnly,
AccessControlType.Allow));
}
// Try to list the security level
public void ShowSecurity(RegistrySecurity security)
{
Console.WriteLine("\r\nCurrent access rules:\r\n");
foreach (RegistryAccessRule ar in security.GetAccessRules(true, true, typeof(NTAccount)))
{
Console.WriteLine(" User: {0}", ar.IdentityReference);
Console.WriteLine(" Type: {0}", ar.AccessControlType);
Console.WriteLine(" Rights: {0}", ar.RegistryRights);
Console.WriteLine(" Inheritance: {0}", ar.InheritanceFlags);
Console.WriteLine(" Propagation: {0}", ar.PropagationFlags);
Console.WriteLine(" Inherited? {0}", ar.IsInherited);
Console.WriteLine();
}
}
}
}

You forgot the 'writable' parameter of the 'OpenSubkey' method.
Try this :
RegistryKey SoftKey = Registry.LocalMachine.OpenSubKey(#"SOFTWARE", true);
It should work like this.
EDIT : This method will probably fail if you don't run Visual Studio as Administrator while debugging.

Related

How to minimize file search runtime complexity?

i wrote an application which is a custom console that allows execution of various commands. One of the commands allows to find a file's full path, according to part of its name. The input data is a string, which equals to part\full name of the file.
My question is - how to minimize the search code runtime complexity as much as possible?
Here is the command's code:
using CustomConsole.Common;
using System;
using System.Collections.Generic;
using System.IO;
namespace Shell_Commander.Commands
{
class FindFileCommand : ICommand
{
private string _findFileCommandName = "findfile";
public string Name { get { return _findFileCommandName; } set { _findFileCommandName = value; } }
public string Execute(string parameters)
{
var fileLocations = new Dictionary<string, bool>();
try
{
var splittedParameters = parameters.Split(" ");
var initialLocation = splittedParameters[0];
var fileName = splittedParameters[1];
foreach (var filePath in Directory.GetFiles(initialLocation, "*.*", SearchOption.A­llDirectories))
{
fileLocations.Add(filePath, false);
if (Path.GetFileName(filePath) == fileName || Path.GetFileNameWithoutExtension(filePath) == fileName)
{
fileLocations[filePath] = true;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
bool fileFound = false;
string returnedOutput = "";
foreach (var location in fileLocations.Keys)
{
if (fileLocations[location])
{
returnedOutput += $"The file found in path: {location}\n";
Console.Write(returnedOutput);
fileFound = true;
}
}
if (!fileFound)
{
returnedOutput = "The file not found in this path";
Console.WriteLine(returnedOutput);
return returnedOutput;
}
return returnedOutput;
}
}
}
Example - for the input parameters "c:\temp test", the output can be:
The file found in path: c:\temp\test.json
The file found in path: c:\temp\test.json
The file found in path: c:\temp\test.xml
The file found in path: c:\temp\test.json
The file found in path: c:\temp\test.xml
The file found in path: c:\temp\test\test.json
You can simply your foreach like this
var fileLocations = Directory.GetFiles(initialLocation, $"{filePath}.*", SearchOption.A­llDirectories);
foreach (var location in fileLocations)
{
returnedOutput += $"The file found in path: {location}\n";
Console.Write(returnedOutput);
}
The rest of the code also can be simplified.

The type or namespace name 'BluetoothAddress' could not be found

I use vs 2017 and windows 7.
I have installed 32feet.NET following this: Looking to write Bluetooth 'hcitool' equivelant in Windows.
But I get the errors:
The type or namespace name 'BluetoothAddress' could not be found
The type or namespace name 'BluetoothClient' could not be found
The type or namespace name 'BluetoothSecurity' could not be found
The type or namespace name 'BluetoothDeviceInfo' could not be found
The type or namespace name 'ServiceRecord' could not be found
I have successfully installed InTheHand.Devices.Bluetooth and There is no warning in the using sentence so the namespace is successfully referenced.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using InTheHand.Devices.Bluetooth;
using InTheHand.Networking;
using InTheHand.Networking.Sockets;
using InTheHand;
using System.Diagnostics;
using System.Net.Sockets;
namespace hcitool
{
partial class Program
{
static bool infoRatherThanName;
static BluetoothAddress _searchAddress;
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Please specify command.");
return 2;
}
var cmd = args[0];
switch (cmd)
{
case "name":
infoRatherThanName = false;
break;
case "info":
infoRatherThanName = true;
break;
//-
case "dev":
return ShowRadios();
//case "auth":
// return CauseAuth(GETADDRESS());
default:
throw new NotImplementedException("Command: '" + cmd + "'");
}
if (args.Length < 2)
{
Console.WriteLine("Please specify device address.");
return 2;
}
var addrS = args[1];
_searchAddress = BluetoothAddress.Parse(addrS);
//
//var dev = new BluetoothDeviceInfo(_searchAddress);
var dev = new BluetoothDevice();
bool isInRange = GetCanConnectTo(dev);
if (isInRange)
{
PrintDevice(dev);
}
else
{
Console.WriteLine("Can't see that device.");
}
//
Console.WriteLine("simple");
return Simple();
//return Fancier();
}
//----
private static int ShowRadios()
{
BluetoothRadio[] list;
try
{
list = BluetoothRadio.AllRadios;
}
catch (Exception)
{
return 1;
}
Debug.Assert(list.Length != 0, "Expect zero radios case to raise an error.");
foreach (var curR in list)
{
Console.WriteLine("* {0} '{1}'", curR.LocalAddress, curR.Name);
Console.WriteLine("{0}", curR.SoftwareManufacturer);
Console.WriteLine("{0}", curR.Manufacturer);
Console.WriteLine("{0}", curR.Mode);
}//for
return 0;
}
private static int CauseAuth(BluetoothAddress addr)
{
BluetoothSecurity.PairRequest(addr, null);
return 0;
}
//----
static int Simple()
{
BluetoothDeviceInfo[] devices;
BluetoothDeviceInfo foundDev = null;
var cli = new BluetoothClient();
// Fast: Remembered/Authenticated
devices = cli.DiscoverDevices(255, true, true, false, false);
SimpleCheckDevice(devices, ref foundDev);
if (foundDev == null)
{
// Slow: Inquiry
cli.DiscoverDevices(255, false, false, true, false);
SimpleCheckDevice(devices, ref foundDev);
}
//
if (foundDev != null)
{
return 0;
}
else
{
return 1;
}
}
private static void SimpleCheckDevice(IEnumerable<BluetoothDeviceInfo> devices,
ref BluetoothDeviceInfo foundDev)
{
foreach (var cur in devices)
{
if (cur.DeviceAddress == _searchAddress)
{
foundDev = cur;
PrintDevice(cur);
}
}//for
}
private static void PrintDevice(BluetoothDeviceInfo cur)
{
Console.WriteLine("* Found device: '{0}' ", cur.DeviceName);
if (infoRatherThanName)
{
try
{
var vs = cur.GetVersions();
Console.WriteLine(vs.Manufacturer);
Console.WriteLine(vs.LmpVersion);
Console.WriteLine(vs.LmpSubversion);
Console.WriteLine(vs.LmpSupportedFeatures);
}
catch (Exception ex)
{
Console.WriteLine("Failed to get remote device versions info: "
+ ex.Message);
}
}
}
//----
private static bool GetCanConnectTo(BluetoothDeviceInfo device)
{
bool inRange;
Guid fakeUuid = new Guid("{F13F471D-47CB-41d6-9609-BAD0690BF891}");
try
{
ServiceRecord[] records = device.GetServiceRecords(fakeUuid);
Debug.Assert(records.Length == 0, "Why are we getting any records?? len: " + records.Length);
inRange = true;
}
catch (SocketException)
{
inRange = false;
}
return inRange;
}
}
}
The BluetoothAddress is in the 32feet.NET nuget package.
You're using the preview version of InTheHand which is missing the BluetoothAddress, the BluetoothRadio, BluetoothDeviceInfo and others.
I think you're referencing the wiki for the 32feet.NET, which is the legacy nuget package.
If you install 32feet.NET v3.5.0.0, you will find all your missing bindings.
Adding 32feet.NET and changing a couple of things:
var dev = new BluetoothDevice();
//this becomes this:
var dev = new BluetoothDeviceInfo(_searchAddress);
it will compile succesfully.
Try to add the following namespaces to your code:
using InTheHand.Net;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;

ClrMD could not attach to process on production server

I am trying to use ClrMD to dump the stacktrace of all threads running within a specific process. The code works fine in my devlopment enviornment but not on the production server.
The server is running: Windows Server 2012 R2 Standard
The error I recieve is:
Could not attach to process. Error 0.
This post asks how to attach ClrMD to another users process, which was what I was trying to do. I terminated the process (which is running as a windows service) and started it as the same user that I am trying to execute ClrMD with. I still get the error.
Tried giving the user debugging privlidges but that didnt help either.
I bet the problem has something to do with how to production server is configured. I have administrator rights.
Any suggestions on what to do next?
Code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Diagnostics.Runtime;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
int pid = 0;
var result = new Dictionary<int, string[]>();
var targetProcessName = "Dist.TingbogScraper.Business.TingbogScraperService.vshost";
// Change this to the process you are looking for
var outputPath = "C:\\temp\\ClrMDresult.txt";
var exceptionOutput = "C:\\temp\\ClrMDdump.txt";
var processes = Process.GetProcesses();
foreach (var process in processes)
{
if (process.ProcessName.Contains(targetProcessName))
{
pid = process.Id;
}
}
try
{
using (var dataTarget = DataTarget.AttachToProcess(pid, 5000, AttachFlag.Passive))
{
ClrRuntime runtime = dataTarget.ClrVersions.First().CreateRuntime();
foreach (var t in runtime.Threads)
{
try
{
if (t.StackTrace != null)
{
result.Add(
t.ManagedThreadId,
t.StackTrace.Select(f =>
{
if (f.Method != null)
{
return f.Method.Type.Name + "." + f.Method.Name;
}
return null;
}).ToArray()
);
}
}
catch (Exception ex)
{
}
}
}
foreach (var kvp in result)
{
var value = kvp.Value;
foreach (var stacktrace in value)
{
System.IO.File.AppendAllText(outputPath,
string.Format("{0} {1} {2}", kvp.Key, stacktrace, Environment.NewLine));
}
}
}
catch (ClrDiagnosticsException ex)
{
System.IO.File.AppendAllText(outputPath,
string.Format("{0} {1} {2}", ex.Message, ex.StackTrace, ex.Source));
}
}
}
}
Found out that the name of the process was different on my development environment compared to production.
Correcting the name of the process fixed the error.

GetExtension method error

I'm getting this error:
would not find a GetExtension method
Code:
public static void Main()
{
string[] arr = {"abc.txt", "asd.TXT","bvc.pdf","fgd.txt","hss.pdf","djhd.xml"};
var arrp = arr.Select(file=>Path.GetExtension(file).TrimStart('.').ToLower()).GroupBy(x=>x,(ext,extcnt)=>new
{
Extension = ext,
count=extcnt.Count()
});
foreach(var v in arrp)
{
Console.WriteLine("{0} files(s) with {1} Extension", v.Count,v.Extension );
Console.ReadLine();
}
}
How can I fix it?
First check, do you have added the using statment? using System.IO;
Second change your code line:
Console.WriteLine("{0} files(s) with {1} Extension", v.Count, v.Extension);
to:
Console.WriteLine("{0} files(s) with {1} Extension", v.count, v.Extension);
i had created a new console application. This example works in my enviroment:
using System;
using System.IO;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] arr = { "abc.txt", "asd.TXT", "bvc.pdf", "fgd.txt", "hss.pdf", "djhd.xml" };
var arrp = arr.Select(file => Path.GetExtension(file).TrimStart('.').ToLower()).GroupBy(x => x, (ext, extcnt) => new
{
Extension = ext,
count = extcnt.Count()
});
foreach (var v in arrp)
{
Console.WriteLine("{0} files(s) with {1} Extension", v.count, v.Extension);
Console.ReadLine();
}
}
}
}
i get this result:
Important: this is a console application! not a asp.net application! (you have added the asp.net tag.. )

Is it possible to delete multiple registry entries one after the other?

I am fairly new to c#. I would like to achieve deleting multiple registry entries one after the other but I am getting exception for the first key and after that the code stops deleting other keys.I have tried below mentioned code it works for single key in if block
string[] keyArray = { #"Wow6432Node\CLSID",
#"Software\Microsoft\Windows\CurrentVersion\Ext\Settings",
#"Software\Microsoft\Windows\CurrentVersion\Ext\Stats",
#"SOFTWARE\Classes\Wow6432Node\CLSID",
#"SOFTWARE\Wow6432Node\Classes\CLSID",
#"Wow6432Node\Microsoft\Code Store Database\Distribution Units",
#"Wow6432Node\Microsoft\Internet Explorer\ActiveX Compatibility",
#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\ModuleUsage"
};
foreach (var key in keyArray)
{
try
{
RegistryKey myKey = Registry.ClassesRoot.OpenSubKey(key, true);
if (myKey != null)
{
/*Cisco Secure Desktop*/
myKey.DeleteSubKeyTree("{705EC6D4-B138-4079-A307-EF13E4889A82}");
myKey.DeleteSubKeyTree("{F8FC1530-0608-11DF-2008-0800200C9A66}");
myKey.DeleteSubKeyTree("{E34F52FE-7769-46CE-8F8B-5E8ABAD2E9FC}");
/*Cisco Hostscan*/
myKey.DeleteSubKeyTree("{F8FC1530-0608-11DF-2008-0800200C9A66}");
myKey.DeleteSubKeyTree("{E34F52FE-7769-46CE-8F8B-5E8ABAD2E9FC}");
/*Cisco AnyConnect Secure Mobility Client*/
myKey.DeleteSubKeyTree("{55963676-2F5E-4BAF-AC28-CF26AA587566}");
myKey.DeleteSubKeyTree("{CC679CB8-DC4B-458B-B817-D447B3B6AC31}");
}
else
Console.WriteLine(string.Format("could not open key: {0}", key));
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(
string.Format("action {0} failed with\n{1}", key, ex.Message));
}
}
Given to your details you may try the following code
string[] keyArray = { #"Wow6432Node\CLSID",
#"Software\Microsoft\Windows\CurrentVersion\Ext\Settings",
#"Software\Microsoft\Windows\CurrentVersion\Ext\Stats",
#"Wow6432Node\Microsoft\Code Store Database\Distribution Units",
#"Wow6432Node\Microsoft\Internet Explorer\ActiveX Compatibility",
#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\ModuleUsage",
#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\ModuleUsage",
};
foreach (var key in keyArray)
{
try
{
RegistryKey myKey = Registry.ClassesRoot.OpenSubKey(key, true);
if (myKey != null)
myKey.DeleteSubKeyTree("{55963676-2F5E-4BAF-AC28-CF26AA587566}");
else
System.Diagnostics.Debug.WriteLine(string.Format("could not open key: {0}", key));
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(
string.Format("action {0} failed with\n{1}", key, ex.Message));
}
}
This should print out some error information, too.
As of your given comment ArgumentException(...) you try to open/delete a subkey {55963676-2F5E-4BAF-AC28-CF26AA587566} that does not exist! Perhaps you should have a look into Registry.OpenSubKey and DeleteSubKeyTree(..)
EDIT: added a new answer as of given details
private static void deleteRegistryKeys2()
{
string[] classIds = {
"{538793D5-659C-4639-A56C-A179AD87ED44}",
/*Cisco Secure Desktop*/
"{705EC6D4-B138-4079-A307-EF13E4889A82}",
"{F8FC1530-0608-11DF-2008-0800200C9A66}",
/*Cisco Hostscan*/
"{F8FC1530-0608-11DF-2008-0800200C9A66}",
"{E34F52FE-7769-46CE-8F8B-5E8ABAD2E9FC}",
/*Cisco AnyConnect Secure Mobility Client*/
"{55963676-2F5E-4BAF-AC28-CF26AA587566}",
"{CC679CB8-DC4B-458B-B817-D447B3B6AC31}"
};
string[] regKeys = { #"Wow6432Node\CLSID",
#"Software\Microsoft\Windows\CurrentVersion\Ext\Settings",
#"Software\Microsoft\Windows\CurrentVersion\Ext\Stats",
#"SOFTWARE\Classes\Wow6432Node\CLSID",
#"SOFTWARE\Wow6432Node\Classes\CLSID",
#"Wow6432Node\Microsoft\Code Store Database\Distribution Units",
#"Wow6432Node\Microsoft\Internet Explorer\ActiveX Compatibility",
#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\ModuleUsage"
};
// iterate every regKey
foreach (var regkey in regKeys)
{
// go for each classId
foreach (var classId in classIds)
{
// get a regKey within a hive, pass classId too
deleteKey(Registry.ClassesRoot.OpenSubKey(regkey, true), classId);
deleteKey(Registry.CurrentUser.OpenSubKey(regkey, true), classId);
deleteKey(Registry.LocalMachine.OpenSubKey(regkey, true), classId);
}
}
Console.WriteLine("Cleanup finished. Press any key to exit");
Console.ReadLine();
}
private static void deleteKey(RegistryKey registryKey, string classId)
{
// check if there is a key
if (registryKey != null)
{
try
{
// try to remove classId within this regKey
registryKey.DeleteSubKeyTree(classId);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
Console.WriteLine(
string.Format("could not delete key {0} with classId {1}",
registryKey, classId));
}
}
}
Finally I have better code which is working after lot of effort Please let me know if anyone can do it better
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] clsids = {
"{538793D5-659C-4639-A56C-A179AD87ED44}",
/*Cisco Secure Desktop*/
"{705EC6D4-B138-4079-A307-EF13E4889A82}",
"{F8FC1530-0608-11DF-2008-0800200C9A66}",
/*Cisco Hostscan*/
"{F8FC1530-0608-11DF-2008-0800200C9A66}",
"{E34F52FE-7769-46CE-8F8B-5E8ABAD2E9FC}",
/*Cisco AnyConnect Secure Mobility Client*/
"{55963676-2F5E-4BAF-AC28-CF26AA587566}",
"{CC679CB8-DC4B-458B-B817-D447B3B6AC31}"
};
string[] keys = { #"Wow6432Node\CLSID",
#"Software\Microsoft\Windows\CurrentVersion\Ext\Settings",
#"Software\Microsoft\Windows\CurrentVersion\Ext\Stats",
#"SOFTWARE\Classes\Wow6432Node\CLSID",
#"SOFTWARE\Wow6432Node\Classes\CLSID",
#"Wow6432Node\Microsoft\Code Store Database\Distribution Units",
#"Wow6432Node\Microsoft\Internet Explorer\ActiveX Compatibility",
#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\ModuleUsage"
};
/*Classes root hive*/
for (int i = 0; i<=7; i++ )
{
foreach (var regkey in keys)
{
try
{
using (RegistryKey mykey = Registry.ClassesRoot.OpenSubKey(regkey, true))
if (mykey != null)
{
Console.WriteLine(mykey + #"\"+clsids[i]);
mykey.DeleteSubKeyTree(clsids[i]);
}
else
{
Console.WriteLine("key does not exist");
}
/*try end*/
}
catch
{
continue;
}
}
}
/*Current user hive*/
for (int i = 0; i <= 7; i++)
{
foreach (var regkey in keys)
{
try
{
using (RegistryKey mykey = Registry.CurrentUser.OpenSubKey(regkey, true))
if (mykey != null)
{
Console.WriteLine(mykey + #"\" + clsids[i]);
mykey.DeleteSubKeyTree(clsids[i]);
}
else
{
Console.WriteLine("key does not exist");
}
/*try end*/
}
catch
{
continue;
}
}
}
/*Local Machine hive*/
for (int i = 0; i <= 7; i++)
{
foreach (var regkey in keys)
{
try
{
using (RegistryKey mykey = Registry.LocalMachine.OpenSubKey(regkey, true))
if (mykey != null)
{
Console.WriteLine(mykey + #"\" + clsids[i]);
mykey.DeleteSubKeyTree(clsids[i]);
}
else
{
Console.WriteLine("key does not exist");
}
/*try end*/
}
catch
{
continue;
}
}
}
Console.WriteLine("Cleanup finished. Press any key to exit");
Console.ReadLine();
}
}
}

Categories

Resources