Listing all children of a process - c#

I'm trying to list all the children of a given process (given it's process ID).
After some research I have come to this:
static void Main(string[] args)
{
listChildProcesses(0);
Console.ReadKey();
}
public static void listChildProcesses(int parentProcessId)
{
String myQuery = string.Format("select * from win32_process where ParentProcessId={0}", parentProcessId);
ObjectQuery objQuery = new ObjectQuery(myQuery);
ManagementObjectSearcher objSearcher = new ManagementObjectSearcher(objQuery);
ManagementObjectCollection processList = objSearcher.Get();
foreach (ManagementObject item in processList)
{
try
{
int processId = Convert.ToInt32(item["ProcessId"].ToString());
Console.WriteLine("processId:{0} name:{1} {2}",
item["ProcessId"],
item["Name"],
item["ParentProcessId"]
);
// recursive call
if (processId != parentProcessId)
listChildProcesses(processId);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
}
}
}
I was hoping this would allow me to display all processes (since the method starts at PID=0 and then is recursively called on each PID found from there).
But here is the output I get on my Windows 8 (x86):
processId:0 name:System Idle Process 0
processId:4 name:System 0
processId:300 name:smss.exe 4
It stops there. I would expect it to keep going on with each child of System and then each child of those children.

You're not doing what you're thinking...
that way you're just listing children. And you're accessing the idle one by '0'.
Try something like this to get all processes...
ManagementClass mngcls = new ManagementClass("Win32_Process");
foreach (ManagementObject instance in mngcls.GetInstances())
{
Console.Write("ID: " + instance["ProcessId"]);
}
...then what you're doing.

Related

How to get the path of a system file

Is there a way to get the path of the system files like "wininit.exe" from processId? Below code doesn't work. Process.GetProcesses() also doesn't return anything logical. Please help me.
P.S. I'm trying to code my own task manager designed based on my needs.
private static string GetMainModuleFilepath(int processId)
{
string wmiQueryString = "SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
{
using (var results = searcher.Get())
{
ManagementObject mo = results.Cast<ManagementObject>().FirstOrDefault();
if (mo != null)
{
return (string)mo["ExecutablePath"];
}
}
}
return null;
}
You can use the Process.GetProcessById method and pass in the ProcessId.
Then you can use the MainModule.FileName property on the ProcessModule.
My full code can be seen below: (I have done this in a Console App for quicker writing)
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Enter Process ID:");
var processIdString = Console.ReadLine();
var parsed = int.TryParse(processIdString, out var procId);
if (parsed)
{
var path = GetMainModuleFilepath(procId);
Console.WriteLine($"Found Path: {path}");
}
else
{
Console.WriteLine("Process Id must be a number!");
}
}
}
private static string GetMainModuleFilepath(int processId)
{
var process = Process.GetProcessById(processId);
if (process == null)
{
return string.Empty;
}
return process.MainModule?.FileName;
}
Which results in the following:
Note:
If you are running this code in 32 bit application, you'll not be able to access 64-bit application paths, so you'd have to compile and run you app as 64-bit application (Project Properties → Build → Platform Target → x64).

Simulate a network failure

I wrote an application using a webservice and I want to simulate a network failure for test purposes. I know I could turn off the network manually, but it would be awesome if it would be automatically.
I tried the solution from: How to simulate network failure for test purposes (in C#)? from Larsenal but it doesn't recognize the ManagementClass/ObjectCollection/... and I don't know why (i used System.Managment.Man... and it still didn't work. I imported the required references - didn't work. I have no idea what I am doing wrong)
It should work something like this:
[TestMethod]
public void Service_Login_NoInternetConnection()
{
// Some code...
TurnOffNetworkConnection();
// More code...
TurnOnNetworkConnection();
// Blablabla code...
}
You can use WMI for it.
First make sure you add reference : System.Management
Then I get all devices with :
"ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_NetworkAdapterConfiguration");"
Now i need to check if a device got DHCPLeaseObtained.
So I use foreach to check every network device in the searcher :
String Check = Convert.ToString(queryObj["DHCPLeaseObtained"]);
If the device has no DHCPLeaseObtained the string will be emty.
So I check if the string is emty :
if (String.IsNullOrEmpty(Check))
Then you can use ReleaseDHCPLease and RenewDHCPLease in the else.
ManagementBaseObject outParams = queryObj.InvokeMethod("ReleaseDHCPLease", null, null);
or
ManagementBaseObject outParams = queryObj.InvokeMethod("RenewDHCPLease", null, null);
using System.Management;
public void TurnOnNetworkConnection()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_NetworkAdapterConfiguration");
foreach (ManagementObject queryObj in searcher.Get())
{
String Check = Convert.ToString(queryObj["DHCPLeaseObtained"]);
if (String.IsNullOrEmpty(Check))
{
}
else
{
ManagementBaseObject outParams = queryObj.InvokeMethod("RenewDHCPLease", null, null);
}
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
public void TurnOffNetworkConnection()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_NetworkAdapterConfiguration");
foreach (ManagementObject queryObj in searcher.Get())
{
String Check = Convert.ToString(queryObj["DHCPLeaseObtained"]);
if (String.IsNullOrEmpty(Check))
{
}
else
{
ManagementBaseObject outParams = queryObj.InvokeMethod("ReleaseDHCPLease", null, null);
}
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}

SoftwareLicensingProduct Which one is my

I need to check whether the OS needs activation,
my following code displays a multitude of "channels".
static void Main(string[] args)
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher
(
"root\\CIMV2",
"SELECT
Description,
LicenseIsAddon,
LicenseStatus
FROM SoftwareLicensingProduct
WHERE LicenseIsAddon = False"
);
foreach (ManagementObject queryObj in searcher.Get())
{
if (queryObj["Description"].ToString().ToLower().Contains("operating"))
{
foreach (var item in queryObj.Properties)
{
Console.WriteLine(item.Value);
}
}
}
Console.Write("***done***");
Console.ReadLine();
}
How do i know which one to check in order to determine if i need to activate the OS?
Or is my only way to see, if i have any LicenseStatus = 1 in there? Which of course can be wrong if there is one activated and one not activated OS installed.
Thanks
For the time being i filtered the channels a bit more and concluded, that this is good enough:
private void getOSActivation()
{
try
{
ManagementObjectSearcher LicenseSearcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT LicenseStatus,Description FROM SoftwareLicensingProduct");
foreach (ManagementObject LSObj in LicenseSearcher.Get())
{
OStestString = LSObj["Description"].ToString().ToLower();
if (
OStestString.Contains("operating")
&&
// next line is new
(OStestString.Contains("slp") || OStestString.Contains("dm"))
)
{
foreach (var item in LSObj.Properties)
{
OSresults.Add(LSObj["LicenseStatus"].ToString());
}
}
}
}
catch (Exception LSOexception)
{
Console.WriteLine(LSOexception.Message);
}
}

Listing USB Devices with C# and WMI

I'm trying to implement a function in my application that lists all the plugged in USB Mass Storage Devices in a computer.
My code works well when launching the application but my problem is that I want the box in my form to refresh automatically when a USB device is removed or attached.
Implementing DBT_DEVICEARRIVAL and DBT_DEVICEREMOVECOMPLETE conditions should work but I get back a "DisconnectedContext was detected" exception.
I learned that I need to use a delegate and set an asyncronous call for this to work correctly.
Here's my code:
public void listUSB()
{
ManagementScope sc = new ManagementScope(wmiUsbList);
ObjectQuery query = new ObjectQuery("select * from Win32_DiskDrive " + "where InterfaceType='USB'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(sc, query);
ManagementObjectCollection result = searcher.Get();
foreach (ManagementObject obj in result)
{
if (obj["DeviceID"] != null)
{
usbListTextBox.AppendText(obj["Model"].ToString());
}
}
}
I'd really like to know how to apply a delegate to my method.
I also looked at this thread on MSDN which provides an excellent example, but as of that example I am not able to understand how to put the deviceList in a textbox.
I'm still Learning so if someone could be so kind to point me to the right direction on one or both of my questions, that would be greatly appreciated.
Thanks!
Try to use ManagementEventWatcher and assign an event handler to the EventArrived.
I don't know how to accomplish exactly this, but here is a watcher that listens to the print events:
string printQuery = "Select * From __InstanceCreationEvent Within 1 Where TargetInstance ISA 'Win32_PrintJob'";
string nspace = #"\\.\root\CIMV2";
var watcher = new ManagementEventWatcher(nspace, printQuery);
Hope it helps.
private usbListArrayDelegate mDeleg;
protected override void WndProc(ref Message m)
{
int devType;
base.WndProc(ref m);
switch (m.WParam.ToInt32())
{
case DBT_DEVICEARRIVAL:
devType = Marshal.ReadInt32(m.LParam, 4);
if (devType == DBT_DEVTYP_VOLUME)
{
// usb device inserted, call the query
mDeleg = new usbListArrayDelegate(usbListArray);
AsyncCallback callback = new AsyncCallback(usbListArrayCallback);
// invoke the thread that will handle getting the friendly names
mDeleg.BeginInvoke(callback, new object());
}
break;
case DBT_DEVICEREMOVECOMPLETE:
devType = Marshal.ReadInt32(m.LParam, 4);
if (devType == DBT_DEVTYP_VOLUME)
{
mDeleg = new usbListArrayDelegate(usbListArray);
AsyncCallback callback = new AsyncCallback(usbListArrayCallback);
// invoke the thread that will handle getting the friendly names
mDeleg.BeginInvoke(callback, new object());
}
break;
}
}
public ArrayList usbListArray()
{
ArrayList deviceList = new ArrayList();
manager = new UsbManager(); ==> about how to implement this please see http://www.codeproject.com/Articles/63878/Enumerate-and-Auto-Detect-USB-Drives
UsbDiskCollection disks = manager.GetAvailableDisks();
foreach (UsbDisk disk in disks)
{
deviceList.Add(disk);
}
return deviceList;
}
// delegate wrapper function for the getFriendlyNameList function
private delegate ArrayList usbListArrayDelegate();
// callback method when the thread returns
private void usbListArrayCallback(IAsyncResult ar)
{
string ArrayData = string.Empty;
// got the returned arrayList, now we can do whatever with it
ArrayList result = mDeleg.EndInvoke(ar);
int count = 0;
foreach (UsbDisk disk in result)
{
++count;
ArrayData += count + ") " + disk.ToString().
}

Need to get name (DeviceID) of System Reserved partition

I need to return the DeviceID of the System Reserved partition. I should be able to do this with the Win32_Volume class by first getting the Label property, and if it matches "System Reserved" then get the DeviceID property. The following code crashes with a null reference exception:
static void Main(string[] args)
{
ManagementObjectSearcher ms = new ManagementObjectSearcher("Select * From Win32_Volume");
foreach (ManagementObject mo in ms.Get())
{
if (mo["Label"].ToString() == "System Reserved")
{
Console.WriteLine(mo["DeviceID"].ToString());
}
}
Console.Read();
}
Here it is for anyone that needs to do this:
string sysGuid = "";
try
{
ManagementObjectSearcher ms = new ManagementObjectSearcher("SELECT * FROM Win32_Volume");
foreach (ManagementObject mo in ms.Get())
{
if (mo["Label"].ToString() == "System Reserved")
{
sysGuid = mo["DeviceID"].ToString();
break;
}
}
}
catch (Exception) {}

Categories

Resources