Hey i have some code to generate Hardware Id for identification and it have worked fine for several month but now without any changes it stopped working it stops at all of these
ManagementObjectCollection cpu_Collection = cpu.Get();
ManagementObjectCollection hdd_Collection = hdd.Get();
ManagementObjectCollection bios_Collection = bios.Get();
Can anyone help me fix it this is all of my code to get the hardware id
//public static string test = ReturnHardwareID().ToString();
private static async Task<string> ReturnHardwareID()
{
byte[] bytes;
byte[] hashedBytes;
StringBuilder sb = new StringBuilder();
Task task = Task.Run(() =>
{
ManagementObjectSearcher cpu = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
ManagementObjectCollection cpu_Collection = cpu.Get();
foreach (ManagementObject obj in cpu_Collection)
{
sb.Append(obj["ProcessorId"].ToString().Substring(0, 4));
break;
}
ManagementObjectSearcher hdd = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
ManagementObjectCollection hdd_Collection = hdd.Get();
foreach (ManagementObject obj in hdd_Collection)
{
sb.Append(obj["Model"].ToString().Substring(0, 4));
break;
}
ManagementObjectSearcher bios = new ManagementObjectSearcher("SELECT * FROM Win32_BIOS");
ManagementObjectCollection bios_Collection = bios.Get();
foreach (ManagementObject obj in bios_Collection)
{
sb.Append(obj["Version"].ToString().Substring(0, 4));
break;
}
});
Task.WaitAll(task);
bytes = Encoding.UTF8.GetBytes(sb.ToString());
hashedBytes = SHA256.Create().ComputeHash(bytes);
return await Task.FromResult(Convert.ToBase64String(hashedBytes).Substring(25));
}
i have copied the code , i have a variable ("Modifiedtime_1.Modifiedtime") i want to change system time with the datetime available in (Modifiedtime_1.Modifiedtime) whenever
if (compare == 0 || compare > 0)
{
Modifiedtime_1.Modifiedtime = Max.AddMinutes(5);
Console.WriteLine("----------");
Console.WriteLine("modifiedtime");
Console.WriteLine(Modifiedtime_1.Modifiedtime);
Console.WriteLine("----------");
}
Loop is executed.
Thanks in adavnce.
using System;
using System.Management;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace datetime_1
{
public class RemoteConnect
{
public class Modifiedtime_1
{
public static DateTime? Modifiedtime = null;
}
public static void Main()
{
while (true)
{
Console.WriteLine(DateTime.Now.ToString());
Console.WriteLine("\a");
Thread.Sleep(1000);
Console.Clear();
ConnectionOptions options = new ConnectionOptions();
options.EnablePrivileges = true;
options.Impersonation = ImpersonationLevel.Impersonate;
options.Authentication = AuthenticationLevel.Packet;
options.Authority = "ntlmdomain:node1.local";
options.Username = "user1";
options.Password = "xxxxxx";
ManagementScope scope = new ManagementScope(string.Format(#"\\node1\root\cimv2"), options);
scope.Connect();
if (scope.IsConnected == true)
{
Console.WriteLine("node1 Connection Succeeded");
}
else
{
Console.WriteLine("node1 Connection Failed");
}
ConnectionOptions options1 = new ConnectionOptions();
options1.EnablePrivileges = true;
options1.Impersonation = ImpersonationLevel.Impersonate;
options1.Authentication = AuthenticationLevel.Packet;
options1.Authority = "ntlmdomain:node2.local";
options1.Username = "user2";
options1.Password = "xxxxxx";
ManagementScope scope1 = new ManagementScope(string.Format(#"\\node2\root\cimv2"), options1);
scope1.Connect();
if (scope1.IsConnected == true)
{
Console.WriteLine("node2 Connection Succeeded");
}
else
{
Console.WriteLine("node2 Connection Failed");
}
ConnectionOptions options3 = new ConnectionOptions();
options3.EnablePrivileges = true;
options3.Impersonation = ImpersonationLevel.Impersonate;
options3.Authentication = AuthenticationLevel.Packet;
options3.Authority = "ntlmdomain:WORKGROUP";
options3.Username = "user2";
options3.Password = "xxxx";
ManagementScope scope3 = new ManagementScope(string.Format(#"\\node3\root\cimv2"), options3);
scope3.Connect();
if (scope3.IsConnected == true)
{
Console.WriteLine("node3 Connection Succeeded");
}
else
{
Console.WriteLine("node3 Connection Failed");
}
ConnectionOptions options4 = new ConnectionOptions();
options4.EnablePrivileges = true;
options4.Impersonation = ImpersonationLevel.Impersonate;
options4.Authentication = AuthenticationLevel.Packet;
options4.Authority = "ntlmdomain:Workgroup";
options4.Username = "user4";
options4.Password = "xxxxxx";
ManagementScope scope4 = new ManagementScope(string.Format(#"\\node4\root\cimv2"), options4);
scope4.Connect();
if (scope4.IsConnected == true)
{
Console.WriteLine("node4 Connection Succeeded");
}
else
{
Console.WriteLine("node4 Connection Failed");
}
DateTime Localdatetime = DateTime.Now;
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_LocalTime");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("node1");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Date: {0}-{1}-{2}", queryObj["Year"], queryObj["Month"], queryObj["Day"]);
Console.WriteLine("Time: {0}:{1}:{2}", queryObj["Hour"], queryObj["Minute"], queryObj["Second"]);
String node1_Hour_TEMP = queryObj["Hour"].ToString();
String node1_Minute_TEMP = queryObj["Minute"].ToString();
String node1_SECOND_TEMP = queryObj["Second"].ToString();
String node1_Year_TEMP = queryObj["Year"].ToString();
String node1_Month_TEMP = queryObj["Month"].ToString();
String node1_Day_TEMP = queryObj["Day"].ToString();
ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(scope1, query);
foreach (ManagementObject queryObj1 in searcher1.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("node2");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Date: {0}-{1}-{2}", queryObj1["Year"], queryObj1["Month"], queryObj1["Day"]);
Console.WriteLine("Time: {0}:{1}:{2}", queryObj1["Hour"], queryObj1["Minute"], queryObj1["Second"]);
String node2_Hour_TEMP = queryObj1["Hour"].ToString();
String node2_Minute_TEMP = queryObj1["Minute"].ToString();
String node2_SECOND_TEMP = queryObj1["Second"].ToString();
String node2_Year_TEMP = queryObj1["Year"].ToString();
String node2_Month_TEMP = queryObj1["Month"].ToString();
String node2_Day_TEMP = queryObj1["Day"].ToString();
ManagementObjectSearcher searcher2 =
new ManagementObjectSearcher(scope3, query);
foreach (ManagementObject queryObj2 in searcher2.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("node3");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Date: {0}-{1}-{2}", queryObj2["Year"], queryObj2["Month"], queryObj2["Day"]);
Console.WriteLine("Time: {0}:{1}:{2}", queryObj2["Hour"], queryObj2["Minute"], queryObj2["Second"]);
String node3_Hour_TEMP = queryObj2["Hour"].ToString();
String node3_Minute_TEMP = queryObj2["Minute"].ToString();
String node3_SECOND_TEMP = queryObj2["Second"].ToString();
String node3_Year_TEMP = queryObj2["Year"].ToString();
String node3_Month_TEMP = queryObj2["Month"].ToString();
String node3_Day_TEMP = queryObj2["Day"].ToString();
ObjectQuery query4 = new ObjectQuery("SELECT * FROM Win32_LocalTime");
ManagementObjectSearcher searcher4 = new ManagementObjectSearcher(scope4, query);
foreach (ManagementObject queryObj4 in searcher4.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("node4");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Date: {0}-{1}-{2}", queryObj4["Year"], queryObj4["Month"], queryObj4["Day"]);
Console.WriteLine("Time: {0}:{1}:{2}", queryObj4["Hour"], queryObj4["Minute"], queryObj4["Second"]);
String node4_Hour_TEMP = queryObj4["Hour"].ToString();
String node4_Minute_TEMP = queryObj4["Minute"].ToString();
String node4_SECOND_TEMP = queryObj4["Second"].ToString();
String node4_Year_TEMP = queryObj4["Year"].ToString();
String node4_Month_TEMP = queryObj4["Month"].ToString();
String node4_Day_TEMP = queryObj4["Day"].ToString();
//Convert DATE Time String to INT
int node1_Hour;
int.TryParse(node1_Hour_TEMP, out node1_Hour);
int node1_Minute;
int.TryParse(node1_Minute_TEMP, out node1_Minute);
int node1_SECOND;
int.TryParse(node1_SECOND_TEMP, out node1_SECOND);
int node1_YEAR;
int.TryParse(node1_Year_TEMP, out node1_YEAR);
int node1_MONTH;
int.TryParse(node1_Month_TEMP, out node1_MONTH);
int node1_DAY;
int.TryParse(node1_Day_TEMP, out node1_DAY);
DateTime node1_DATE = new DateTime(node1_YEAR, node1_MONTH, node1_DAY, node1_Hour, node1_Minute, node1_SECOND);
//Convert DATE Time String to INT
int node2_Hour;
int.TryParse(node2_Hour_TEMP, out node2_Hour);
int node2_Minute;
int.TryParse(node2_Minute_TEMP, out node2_Minute);
int node2_SECOND;
int.TryParse(node2_SECOND_TEMP, out node2_SECOND);
int node2_YEAR;
int.TryParse(node2_Year_TEMP, out node2_YEAR);
int node2_MONTH;
int.TryParse(node2_Month_TEMP, out node2_MONTH);
int node2_DAY;
int.TryParse(node2_Day_TEMP, out node2_DAY);
DateTime node2_DATE = new DateTime(node2_YEAR, node2_MONTH, node2_DAY, node2_Hour, node2_Minute, node2_SECOND);
//Convert DATE Time String to INT
int node3_Hour;
int.TryParse(node3_Hour_TEMP, out node3_Hour);
int node3_Minute;
int.TryParse(node3_Minute_TEMP, out node3_Minute);
int node3_SECOND;
int.TryParse(node3_SECOND_TEMP, out node3_SECOND);
int node3_YEAR;
int.TryParse(node3_Year_TEMP, out node3_YEAR);
int node3_MONTH;
int.TryParse(node3_Month_TEMP, out node3_MONTH);
int node3_DAY;
int.TryParse(node3_Day_TEMP, out node3_DAY);
DateTime node3_DATE = new DateTime(node3_YEAR, node3_MONTH, node3_DAY, node3_Hour, node3_Minute, node3_SECOND);
//Convert DATE Time String to INT
int node4_Hour;
int.TryParse(node4_Hour_TEMP, out node4_Hour);
int node4_Minute;
int.TryParse(node4_Minute_TEMP, out node4_Minute);
int node4_SECOND;
int.TryParse(node4_SECOND_TEMP, out node4_SECOND);
int node4_YEAR;
int.TryParse(node4_Year_TEMP, out node4_YEAR);
int node4_MONTH;
int.TryParse(node4_Month_TEMP, out node4_MONTH);
int node4_DAY;
int.TryParse(node4_Day_TEMP, out node4_DAY);
DateTime node4_DATE = new DateTime(node4_YEAR, node4_MONTH, node4_DAY, node4_Hour, node4_Minute, node4_SECOND);
Console.WriteLine("LocalDateTime");
Console.WriteLine(Localdatetime);
Console.WriteLine("=====LINQ=====");
var Max = new[] { node1_DATE, node2_DATE, node3_DATE, node4_DATE }.Max();
Console.WriteLine(Max);
Console.WriteLine("=====LINQEND=====");
//compare datetime with local.
int compare = DateTime.Compare(Max, Localdatetime);
if (compare == 0 || compare > 0)
{
Modifiedtime_1.Modifiedtime = Max.AddMinutes(5);
Console.WriteLine("----------");
Console.WriteLine("modifiedtime");
Console.WriteLine(Modifiedtime_1.Modifiedtime);
Console.WriteLine("----------");
}
else
{
Modifiedtime_1.Modifiedtime = Localdatetime;
Console.WriteLine("----------");
Console.WriteLine("modifiedtime");
Console.WriteLine(Modifiedtime_1.Modifiedtime);
Console.WriteLine("----------");
}
}
}
}
}
}
}
}
}
Why not just do something like this
Before your infinite loop.
bool firstPass = true;
Inside your loop
... Work out what Modifiedtime_1.Modifiedtime value is.
and at the end of the loop
if ( firstPass || (..times deviated to much calculation))
{
firstPass = false;
SetLocalMachineTimeMethod(Modifiedtime_1.Modifiedtime);
}
where SetLocalMachineTimeMethod is some routine you call to set the time locally. There is also a possibility of the added refinement of checking the modified time and (local system time) to see if they have drifted apart by too much and then allow the call be be made again.
I'm trying to get two values, DesignCapacity and FullChargeCacity, but they are not returning a value.
I'm using the code below:
public static bool CheckBattery()
{
bool _testResult = false;
string computer = ".";
try
{
ManagementScope scp = new ManagementScope(#"\\" + computer + #"\root\cimv2");
scp.Connect();
SelectQuery sql = new SelectQuery("CIM_Battery");
ManagementObjectSearcher mos = new ManagementObjectSearcher(scp,sql);
ManagementObjectCollection moc = mos.Get();
List<string> resultList = new List<string>();
foreach (ManagementObject o in moc)
{
foreach (PropertyData property in o.Properties)
{
resultList.Add( property.Name + ":" +property.Value);
}
File.WriteAllLines("bat.txt", resultList.ToArray());
//UInt16 availability = (UInt16)o["Availability"];
//resultList.Add("Availability," + availability.ToString());
//UInt16 batterystatus = (UInt16)o["BatteryStatus"];
//resultList.Add("BatteryStatus," + batterystatus.ToString());
//string status = (string)o["Status"];
//resultList.Add("Status," + status);
//UInt32 Desigcap = (UInt32)o["DesignCapacity"];
}
}
catch (Exception ex)
{
string errr = ex.Message;
}
return _testResult;
}
How Can I avoid to get null values in this properties? In fact iterating the objects im getting this information:
Availability:2
BatteryRechargeTime:
BatteryStatus:2
Caption:Internal Battery
Chemistry:2
ConfigManagerErrorCode:?
ConfigManagerUserConfig:?
CreationClassName:Win32_Battery
Description:Internal Battery
DesignCapacity:?
DesignVoltage:17119
DeviceID:3338SANYO AL12A32
ErrorCleared:?
ErrorDescription:?
EstimatedChargeRemaining:100
EstimatedRunTime:71582788
ExpectedBatteryLife:
ExpectedLife:?
FullChargeCapacity:?
InstallDate:?
LastErrorCode:
MaxRechargeTime:
Name:AL12A32
PNPDeviceID:
PowerManagementCapabilities:System.UInt16[]
PowerManagementSupported:False
SmartBatteryVersion:
Status:OK
StatusInfo:?
SystemCreationClassName:Win32_ComputerSystem
SystemName:MX02L180
TimeOnBattery:?
TimeToFullCharge:?
To get those particular values you need to do separate queries against different classes.
DesignCapacity can be queried from BatteryStaticData
FullChargeCacity can be queried from BatteryFullChargedCapacity
You'll need to use a different scope in the code also for the query. These classes are found in root/WMI instead of root/cimv2
string scope = "root/WMI";
string query = "SELECT DesignedCapacity FROM BatteryStaticData";
using (ManagementObjectSearcher batteriesQuery = new ManagementObjectSearcher(scope, query))
{
using (ManagementObjectCollection batteries = batteriesQuery.Get())
{
foreach (ManagementObject battery in batteries)
{
if (battery != null)
{
foreach (var property in battery.Properties)
{
Console.Log("Property name: " + property.Name + " Property value: " + property.Value);
}
}
}
}
}
I wanted to write a code in C# to list all the users/groups having access (Read/Write/Full) to a shared folder on a server.
For Example: I have a shared folder \servername\MyData. Now I wanted to list the users/groups who have access to this folder.
This should get you pointed in the right direction, I can't test it atm but should be something similar.
private bool CheckAccess(DirectoryInfo directory)
{
// Get the collection of authorization rules that apply to the current directory
AuthorizationRuleCollection acl = directory.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
foreach (var rule in acl)
{
// do something here
}
}
private DataTable GetSharedFolderAccessRule()
{
DataTable DT = new DataTable();
try
{
DT.Columns.Add("ShareName");
DT.Columns.Add("Caption");
DT.Columns.Add("Path");
DT.Columns.Add("Domain");
DT.Columns.Add("User");
DT.Columns.Add("AccessMask");
DT.Columns.Add("AceType");
ManagementScope Scope = new ManagementScope(#"\\.\root\cimv2");
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_LogicalShareSecuritySetting");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
ManagementObjectCollection QueryCollection = Searcher.Get();
foreach (ManagementObject SharedFolder in QueryCollection)
{
{
String ShareName = (String) SharedFolder["Name"];
String Caption = (String)SharedFolder["Caption"];
String LocalPath = String.Empty;
ManagementObjectSearcher Win32Share = new ManagementObjectSearcher("SELECT Path FROM Win32_share WHERE Name = '" + ShareName + "'");
foreach (ManagementObject ShareData in Win32Share.Get())
{
LocalPath = (String) ShareData["Path"];
}
ManagementBaseObject Method = SharedFolder.InvokeMethod("GetSecurityDescriptor", null, new InvokeMethodOptions());
ManagementBaseObject Descriptor = (ManagementBaseObject)Method["Descriptor"];
ManagementBaseObject[] DACL = (ManagementBaseObject[])Descriptor["DACL"];
foreach (ManagementBaseObject ACE in DACL)
{
ManagementBaseObject Trustee = (ManagementBaseObject)ACE["Trustee"];
DataRow Row = DT.NewRow();
Row["ShareName"] = ShareName;
Row["Caption"] = Caption;
Row["Path"] = LocalPath;
Row["Domain"] = (String) Trustee["Domain"];
Row["User"] = (String) Trustee["Name"];
Row["AccessMask"] = (UInt32) ACE["AccessMask"];
Row["AceType"] = (UInt32)ACE["AceType"];
DT.Rows.Add(Row);
DT.AcceptChanges();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
return DT;
}
i had written a code to display the description(Name) of connected USB devices.once i removed a device,then i need to refresh the ManagementObject and have to display the connected device description.
Here is my Code,
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_USBControllerDevice");
foreach (ManagementObject mo in searcher.Get())
{
string str1 = mo["CurrentRefreshRate"].ToString();
Console.WriteLine(str1);
string dependent = mo["Dependent"].ToString();
string deviceId = dependent.Split('=')[1];
deviceId = deviceId.Replace('\"', '\'');
ManagementObjectSearcher searcher2 =
new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity Where DeviceID = " + deviceId);
foreach (ManagementObject mo2 in searcher2.Get())
{
HardwareDetails Detail = new HardwareDetails();
Detail.Description = mo2["Description"].ToString();
Detail.DeviceId = mo2["DeviceId"].ToString();
string[] str = Detail.DeviceId.Split('\\');
string Id = str[1];
if (Id.Contains('&'))
{
string[] separate = Id.Split('&');
Detail.Vid = separate[0].Contains('_') ? separate[0].Split('_')[1] : separate[0].Split('D')[1];
Detail.Pid = separate[1].Contains('_') ? separate[1].Split('_')[1] : separate[1].Split('D')[1];
//Detail.Pid = pid1[1];
}
else
{
Detail.Vid = "";
Detail.Pid = "";
}
if (list.Count > 0)
{
foreach (HardwareDetails h in list)
{
if (!(h.Description == Detail.Description))
{
list.Add(Detail);
break;
}
}
}
else
list.Add(Detail);
}
}
// remove duplicates, sort alphabetically and convert to array
HardwareDetails[] usbDevices = list.ToArray();
return usbDevices;
Did you try this?
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM Win32_DeviceChangeEvent");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
watcher.EventArrived +=
new EventArrivedEventHandler(HandleEvent);
// Start listening for events
watcher.Start();
.........
// Stop listening for events
watcher.Stop();
And in the HandleEvent add or remove device from the list
Hope this helps!