private void SetUIEnable(string serviceName) { System.Management.ManagementObject wmi = new System.Management.ManagementObject(string.Format("Win32_Service.Name='{0}'", serviceName)); System.Management.ManagementBaseObject cm = wmi.GetMethodParameters("Change"); cm["DesktopInteract"] = true; System.Management.ManagementBaseObject ut = wmi.InvokeMethod("Change", cm, null); }
private void MainForm_Load(System.Object sender, System.EventArgs e) { try { System.Management.ManagementObject i = null; System.Management.ManagementObjectSearcher searchInfo_Processor = new System.Management.ManagementObjectSearcher("Select * from Win32_Processor"); foreach (System.Management.ManagementObject i_loopVariable in searchInfo_Processor.Get()) { i = i_loopVariable; txtProcessorName.Text = i["Name"].ToString(); txtProcessorID.Text = i["ProcessorID"].ToString(); txtProcessorDescription.Text = i["Description"].ToString(); txtProcessorManufacturer.Text = i["Manufacturer"].ToString(); txtProcessorL2CacheSize.Text = i["L2CacheSize"].ToString(); txtProcessorClockSpeed.Text = i["CurrentClockSpeed"].ToString() + " Mhz"; txtProcessorDataWidth.Text = i["DataWidth"].ToString(); txtProcessorExtClock.Text = i["ExtClock"].ToString() + " Mhz"; txtProcessorFamily.Text = i["Family"].ToString(); } System.Management.ManagementObjectSearcher searchInfo_Board = new System.Management.ManagementObjectSearcher("Select * from Win32_BaseBoard"); foreach (System.Management.ManagementObject i_loopVariable in searchInfo_Board.Get()) { i = i_loopVariable; txtBoardDescription.Text = i["Description"].ToString(); txtBoardManufacturer.Text = i["Manufacturer"].ToString(); txtBoardName.Text = i["Name"].ToString(); txtBoardSerialNumber.Text = i["SerialNumber"].ToString(); } } catch (Exception ex) { Interaction.MsgBox(ex.Message, MsgBoxStyle.Critical, "Error!"); System.Environment.Exit(0); } }
internal static string GetUniqueIdHash() { string uniqueIdHash = "nil"; try { var managementObj = new System.Management.ManagementObject("Win32_OperatingSystem=@"); string serialNumber = (string)managementObj["SerialNumber"]; if (!string.IsNullOrWhiteSpace(serialNumber)) { var serialBytes = Encoding.ASCII.GetBytes(serialNumber); using (var md = new System.Security.Cryptography.MD5CryptoServiceProvider()) // MD5 to keep it short enough as this hash is not used for security in any way { var hash = md.ComputeHash(serialBytes); uniqueIdHash = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); } } } catch (Exception ex) { log.Error(ex); } return(uniqueIdHash); }
private void OnMPCStarted(System.Management.ManagementObject obj) { string args = null; if (m_mpcAPI == null || !m_mpcAPI.isHooked || (UInt32)obj["ProcessID"] != m_mpcAPI.ProcessID) { args = obj["CommandLine"].ToString(); obj.InvokeMethod("Terminate", null); Dispatcher.BeginInvoke(new Action(delegate { if (m_mpcAPI == null || !m_mpcAPI.isHooked) { mpchcLaunch(null, null); } if (args != null) { string[] argsArray = args.Split('"').Where(x => !String.IsNullOrWhiteSpace(x)).ToArray <string>(); foreach (string arg in argsArray) { if (File.Exists(arg) && allowedVideoFiles.Contains(String.Format("*{0}", Path.GetExtension(arg).ToLower()))) { m_mpcAPI.AddFileToPlaylist(arg); } } } })); } }
internal static string GetHwid() { string drive = string.Empty; foreach (System.IO.DriveInfo compDrive in System.IO.DriveInfo.GetDrives()) { if (compDrive.IsReady) { drive = compDrive.RootDirectory.ToString(); break; } } drive = drive.EndsWith(":\\") ? drive.Substring(0, drive.Length - 2) : drive; string volumeSerial = string.Empty; System.Management.ManagementObject disk = new System.Management.ManagementObject(@"win32_logicaldisk.deviceid=""" + drive + @":"""); disk.Get(); volumeSerial = disk["VolumeSerialNumber"].ToString(); disk.Dispose(); string a = Environment.OSVersion.Version.ToString(); string b = volumeSerial; string c = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].GetPhysicalAddress().ToString(); return(a + b + c); }
protected override void OnStarting() { var isRelease = true; #if DEBUG isRelease = false; #endif var logLines = new string[6]; if (isRelease) { logLines[1] = $"| RELEASE build detected"; } else { logLines[1] = $"| DEBUG build detected"; } int workerThreads; int completionPortThreads; ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); var processorCount = Environment.ProcessorCount; var mo = new System.Management.ManagementObject("Win32_Processor.DeviceID='CPU0'"); var cpuSpeed = (uint)(mo["CurrentClockSpeed"]); mo.Dispose(); logLines[0] = $"| Starting {this.Name} microservice..."; logLines[2] = string.Format("| Worker threads: {0}", workerThreads); logLines[3] = string.Format("| OSVersion: {0}", Environment.OSVersion); logLines[4] = string.Format("| ProcessorCount: {0}", processorCount); logLines[5] = string.Format("| ClockSpeed: {0} MHZ", cpuSpeed); this.log.Log($"", logLines); }
private static void SetInterActWithDeskTop() { var service = new System.Management.ManagementObject(string.Format("WIN32_Service.Name='{0}'", "DataCollector.JobService")); try { //var paramList = new object[11]; //paramList[5] = true; //service.InvokeMethod("Change", paramList); var desktopInteractProp = getPropertiesList(service.Properties). First(p => p.Name.ToLowerInvariant() == "DesktopInteract".ToLowerInvariant()); //desktopInteractProp.Value = true; //var servMethodParams = service.GetMethodParameters("Change"); //var desktopInteractProp = getPropertiesList(servMethodParams.Properties) // .First(p => p.Name.ToLowerInvariant() == "DesktopInteract".ToLowerInvariant()); desktopInteractProp.Value = true; //service.InvokeMethod("Change", servMethodParams, null); //service.InvokeMethod("Change", servMethodParams.Properties); } finally { service.Dispose(); } }
private void bnSelectPath_Click(object sender, RoutedEventArgs e) { TextBox tb = (sender == bnSelectAnswerPath) ? tbAnswerPath : (sender == tbTrackingPathLocal ? tbTrackingPathLocal : tbTrackingPathRemote); String newPath = FileDialogs.SelectFolder(tb.Text); if (newPath != null && System.IO.Path.IsPathRooted(newPath) && !newPath.StartsWith("\\\\")) { DriveInfo di = new DriveInfo(newPath.Substring(0, 2)); if (di.DriveType == DriveType.Network) { System.Management.SelectQuery sq = new System.Management.SelectQuery("Win32_LogicalDisk"); System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(sq); foreach (System.Management.ManagementObject drive in mos.Get()) { String path = drive.Path.ToString(); if (path.Contains(newPath.Substring(0, 2))) { System.Management.ManagementObject nwd = new System.Management.ManagementObject(drive.Path); UInt32 driveType = Convert.ToUInt32(nwd["DriveType"]); foreach (System.Management.PropertyData prop in nwd.Properties) { if (prop.Name == "ProviderName") { newPath = Convert.ToString(prop.Value) + newPath.Remove(0, 2); break; } } } } } tb.Text = newPath; } }
private Dictionary <SystemServiceProperty, object> GetServiceProperties() { if (GetStatus() == SystemServiceStatus.NotInstalled) { return(new Dictionary <SystemServiceProperty, object>()); } var serviceProperties = new Dictionary <SystemServiceProperty, object>(); var service = new System.Management.ManagementObject(String.Format("WIN32_Service.Name='{0}'", ServiceName)); foreach (var property in service.Properties) { SystemServiceProperty systemServiceProperty; bool isProperty = Enum.TryParse <SystemServiceProperty>(property.Name, out systemServiceProperty); if (isProperty) { serviceProperties.Add(systemServiceProperty, property.Value); } } return(serviceProperties); }
private static void PrintSystemInfo(ILogger log, int processorsCount) { int workerThreads; int completionPortThreads; ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); var processorCount = Environment.ProcessorCount; var mo = new System.Management.ManagementObject("Win32_Processor.DeviceID='CPU0'"); var cpuSpeed = (uint)(mo["CurrentClockSpeed"]); mo.Dispose(); var logLines = new string[6]; #if !DEBUG logLines[0] = $"| RELEASE build detected"; #endif #if DEBUG logLines[0] = $"| DEBUG build detected"; #endif logLines[1] = string.Format("| Worker threads: {0}", workerThreads); logLines[2] = string.Format("| OSVersion: {0}", Environment.OSVersion); logLines[3] = string.Format("| ProcessorCount: {0}", processorCount); logLines[4] = string.Format("| ClockSpeed: {0} MHZ", cpuSpeed); logLines[5] = $"| MicroserviceCount: {processorsCount}"; log.Log($"Starting Event Centric System...", logLines); }
static private string GetDiskVolumeSerialNumber() { System.Management.ManagementClass mc = new System.Management.ManagementClass("win32_NetWorkAdapterConfiguration"); System.Management.ManagementObject disk = new System.Management.ManagementObject("win32_logicaldisk.deviceid=\"d:\""); disk.Get(); return(disk.GetPropertyValue("VolumeSerialNumber").ToString()); }
public Service1C(System.Management.ManagementObject sc) { this.Name = (String)sc["name"]; this.Path = (String)sc["PathName"]; this.State = (String)sc["State"]; this.Status = (String)sc["Status"]; this.StartMode = (String)sc["StartMode"]; }
private static void ReflectObjectInModel(System.Management.ManagementObject obj, ProcessInfo pInfo, string owner) { pInfo.Id = (uint)obj["ProcessId"]; pInfo.Name = (string)obj["Name"]; pInfo.Owner = owner; pInfo.ExecPath = (string)obj["ExecutablePath"]; pInfo.Memory = (ulong)obj["WorkingSetSize"] / 1024.0 / 1024.0; pInfo.ThreadCount = (uint)obj["ThreadCount"]; }
internal static MsDnsARecord Parse(System.Management.ManagementObject record, MsDnsZone zone) { MsDnsARecord dnsRecord = new MsDnsARecord( (string)record.Properties["OwnerName"].Value, (string)record.Properties["RecordData"].Value, zone, (int)(UInt32)record.Properties["TTL"].Value); return(dnsRecord); }
public static uint CpuSpeed() { #if THREADS var mo = new System.Management.ManagementObject("Win32_Processor.DeviceID='CPU0'"); var sp = (uint)(mo["CurrentClockSpeed"]); mo.Dispose(); return(sp); #else return(0); #endif }
/// <summary> /// Will return null if the disk parameters could not be determined. /// </summary> /// <param name="path">An absolute path</param> /// <exception cref="Exception">May be thrown</exception>> public static DiskSpaceInfo GetDiskSpaceInfo(string path) { string DriveLetter = Path.GetPathRoot(path).TrimEnd('\\'); var o = new System.Management.ManagementObject($"Win32_LogicalDisk.DeviceID=\"{DriveLetter}\""); string fsType = o.Properties["FileSystem"].Value.ToString(); bool isFAT = (fsType == "FAT" || fsType == "FAT32"); UInt64 freeBytes = UInt64.Parse(o.Properties["FreeSpace"].Value.ToString()); UInt64 totalBytes = UInt64.Parse(o.Properties["Size"].Value.ToString()); return(new DiskSpaceInfo(freeBytes, totalBytes, isFAT)); }
/// <summary> /// Get volume serial number of drive C /// </summary> /// <returns></returns> private static string GetDiskVolumeSerialNumber() { try { var _disk = new System.Management.ManagementObject(@"Win32_LogicalDisk.deviceid=""c:"""); _disk.Get(); return(_disk["VolumeSerialNumber"].ToString()); } catch { return(string.Empty); } }
public static string LicenseString() { using (var mo = new System.Management.ManagementObject("Win32_OperatingSystem=@")) { //プロダクトID string SerialNumber = (string)mo["SerialNumber"]; //ホスト名 string CSName = (string)mo["CSName"]; return(HashString(SerialNumber.ToUpper(), CSName.ToUpper()).Replace("+", "").Replace("/", "").Replace("=", "").Substring(0, 10)); } }
public static object TryGetProperty(this System.Management.ManagementObject wmiObj, string propertyName) { object retval; try { retval = wmiObj.GetPropertyValue(propertyName); } catch (System.Management.ManagementException ex) { retval = ""; } return(retval); }
protected override void OnAfterInstall(IDictionary savedState) { try { base.OnAfterInstall(savedState); System.Management.ManagementObject myService = new System.Management.ManagementObject( string.Format("Win32_Service.Name='{0}'", this.serviceInstaller1.ServiceName)); System.Management.ManagementBaseObject changeMethod = myService.GetMethodParameters("Change"); changeMethod["DesktopInteract"] = true;//允许服务与桌面交互 System.Management.ManagementBaseObject OutParam = myService.InvokeMethod("Change", changeMethod, null); } catch (Exception) { } }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.cDrive = new System.Management.ManagementObject(); this.win32LogicalDisk = new System.Management.ManagementObject(); //@design cDrive.SetLocation(new System.Drawing.Point(116, 7)); //@design win32LogicalDisk.SetLocation(new System.Drawing.Point(7, 7)); this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.Text = "Form1"; //@design this.TrayLargeIcon = true; //@design this.TrayHeight = 201; this.ClientSize = new System.Drawing.Size(352, 277); }
private static void SetInterActWithDeskTop() { var service = new System.Management.ManagementObject( String.Format("WIN32_Service.Name='{0}'", "ServiceCrc")); try { var paramList = new object[11]; paramList[5] = true; service.InvokeMethod("Change", paramList); } finally { service.Dispose(); } }
/// <summary> /// Gets total size of the specified disk. /// </summary> /// <param name="disk">The disk to obtain the information for.<param> /// <returns>Returns total size of the specified disk.</returns> public static long GetDiskSize(string disk) { long result = 0; try { string root = System.IO.Path.GetPathRoot(System.IO.Path.GetFullPath(disk)); root = root.Replace(@"\", ""); System.Management.ManagementObject theDisk = new System.Management.ManagementObject("win32_logicaldisk.deviceid=\"" + root + "\""); theDisk.Get(); result = System.Convert.ToInt64(theDisk["Size"]); } catch { } return(result); }
private void vInitializeRegistryToInteractWithDesktop() { try { System.Management.ConnectionOptions coOptions = new System.Management.ConnectionOptions(); coOptions.Impersonation = System.Management.ImpersonationLevel.Impersonate; System.Management.ManagementScope mgmtScope = new System.Management.ManagementScope(@"root\CIMV2", coOptions); mgmtScope.Connect(); System.Management.ManagementObject wmiService; wmiService = new System.Management.ManagementObject("Win32_Service.Name='" + mdlConstantes.clsConstantes.WINDOWSSERVICE_SISCOMENSAGEM_NAME + "'"); System.Management.ManagementBaseObject InParam = wmiService.GetMethodParameters("Change"); InParam["DesktopInteract"] = true; System.Management.ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null); } catch { // Cant access the registry } }
/// <summary> /// Will return null if the disk parameters could not be determined. /// </summary> /// <param name="path">An absolute path</param> /// <returns></returns> public static DiskSpaceInfo GetDiskSpaceInfo(string path) { try { string DriveLetter = Path.GetPathRoot(path).TrimEnd(new char[] { '\\' }); System.Management.ManagementObject o = new System.Management.ManagementObject( string.Format("Win32_LogicalDisk.DeviceID=\"{0}\"", DriveLetter)); string fsType = o.Properties["FileSystem"].Value.ToString(); bool isFAT = (fsType == "FAT" || fsType == "FAT32"); UInt64 freeBytes = UInt64.Parse(o.Properties["FreeSpace"].Value.ToString()); UInt64 totalBytes = UInt64.Parse(o.Properties["Size"].Value.ToString()); return(new DiskSpaceInfo(freeBytes, totalBytes, isFAT)); } catch (Exception exn) { log.Warn(exn, exn); return(null); } }
/// <summary> /// 取消共享指定目录。 /// </summary> /// <param name="ShareName">共享名称。</param> public void DeleteShare(string ShareName) { System.Management.ManagementObject classInstance = new System.Management.ManagementObject(@"root\CIMV2", "Win32_Share.Name='" + ShareName + @"'", null); System.Management.ManagementBaseObject outParams = classInstance.InvokeMethod("Delete", null, null); switch ((uint)outParams.Properties["ReturnValue"].Value) { case 0: //Success break; case 2: //Access denied throw new System.Exception("无权访问"); case 8: //Unknown failure throw new System.Exception("未知失败"); case 9: //Invalid name throw new System.Exception("非法的共享名"); case 10: //Invalid level throw new System.Exception("非法的层次"); case 21: //Invalid parameter throw new System.Exception("非法的参数"); case 22: //Duplicate share throw new System.Exception("重复共享"); case 23: //Redirected path throw new System.Exception("重定向路径"); case 24: //Unknown device or directory throw new System.Exception("未知的目录"); case 25: //Net name not found throw new System.Exception("网络名不存在"); default: throw new System.Exception("未知异常信息"); } }
public static void SetNewDefaultPrinter(string newDefaultPrinterName) { string selectAllQuery = "SELECT * FROM Win32_Printer"; System.Management.ObjectQuery oq = new System.Management.ObjectQuery(selectAllQuery); System.Management.ManagementObjectSearcher query1 = new System.Management.ManagementObjectSearcher(oq); System.Management.ManagementObjectCollection queryCollection1 = query1.Get(); System.Management.ManagementObject newDefault = null; foreach (System.Management.ManagementObject mo in queryCollection1) { System.Management.PropertyDataCollection pdc = mo.Properties; if (mo["Name"].ToString().ToUpper().Trim() == newDefaultPrinterName.ToUpper()) { newDefault = mo; break; } } if (newDefault != null) { System.Management.ManagementBaseObject outParams = newDefault.InvokeMethod("SetDefaultPrinter", null, null); string returnValue = outParams["returnValue"].ToString(); if (returnValue != "0") { throw new ApplicationException(string.Format("Change Printer '{0}' failed. Return Value: {1}", newDefault.ToString(), returnValue)); } var HWND_BROADCAST = new IntPtr(0xffff); uint WM_SETTINGCHANGE = 0x001A; UIntPtr innerPinvokeResult; var pinvokeResult = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, UIntPtr.Zero, IntPtr.Zero, SendMessageTimeoutFlags.SMTO_NORMAL, 1000, out innerPinvokeResult); } else { throw new ApplicationException(string.Format("Change Printer '{0}' failed. Managemengt object not found", newDefaultPrinterName)); } }
/// <summary> /// Получает название физического диска используя механизм WMI, если название не найдено - возвращает пустую строку /// </summary> /// <param name="driveLetter">Буква логического тома</param> /// <returns>Название физического диска вида \\.\PHYSICALDRIVEX</returns> public static string GetPhysicalDriveName(string driveLetter) { //MessageBox.Show(RPD.DAL.WinAPI.GetPhysicalDeviceName("C")); //System.IO.DriveInfo x = new System.IO.DriveInfo("C"); //System.IO. //MessageBox.Show(x.Name); if (driveLetter.Length == 1) { using (System.Management.ManagementObject mo = new System.Management.ManagementObject(@"Win32_LogicalDisk='" + driveLetter + ":'")) { foreach (System.Management.ManagementObject b in mo.GetRelated("Win32_DiskPartition")) { foreach (System.Management.ManagementBaseObject c in b.GetRelated("Win32_Diskdrive")) { //Console.WriteLine("{0}", c["Name"]); return(c["Name"].ToString()); } } } } return(""); }
public String GetOSBits() { using (System.Management.ManagementObject mo = new System.Management.ManagementObject("Win32_Processor.DeviceID='CPU0'")) { ushort procArch = (ushort)mo["Architecture"]; if (procArch == 0) { //x86 return("32"); } else if (procArch == 9) { //x64 return("64"); } else if (procArch == 6) { return("ia64"); } return("?"); } }
private void SetServiceProperties(Dictionary <SystemServiceProperty, object> serviceProperties, bool restart) { if (GetStatus() == SystemServiceStatus.NotInstalled) { return; } var service = new System.Management.ManagementObject(String.Format("WIN32_Service.Name='{0}'", ServiceName)); try { var paramList = new object[11]; foreach (KeyValuePair <SystemServiceProperty, object> kvp in serviceProperties) { SystemServiceProperty systemServiceProperty = kvp.Key; object servicePropertyValue = kvp.Value; TypeAttribute typeAttribute = systemServiceProperty.GetEnumAttribute <TypeAttribute>(); paramList[(int)systemServiceProperty] = Convert.ChangeType(servicePropertyValue, typeAttribute.Type); } var output = (int)service.InvokeMethod("Change", paramList); if (output != 0) { throw new Exception(string.Format("FAILED with code {0}", output)); } if (restart) { Stop(); Start(); } } finally { service.Dispose(); } }
public Logicaldisk(System.Management.ManagementObject theObject) { if ((CheckIfProperClass(theObject) == true)) { PrivateLateBoundObject = theObject; PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); curObj = PrivateLateBoundObject; } else { throw new System.ArgumentException("Klassenname stimmt nicht überein."); } }
public static List<Dictionary<string, string>> SystemProfileForHost(SUHost host) { List<Dictionary<string, string>> profile = new List<Dictionary<string, string>>(); // App name profile.Add(DictionaryForProfileItem("appName", SULocalizedStrings.StringForKey("Application Name"), host.Name, host.Name)); // App version profile.Add(DictionaryForProfileItem("appVersion", SULocalizedStrings.StringForKey("Application Version"), host.Version, host.Version)); // System version string version = Environment.OSVersion.ToString(); profile.Add(DictionaryForProfileItem("osVersion", SULocalizedStrings.StringForKey("OS Version"), version, version)); // .NET version string frameworkVersion = Environment.Version.ToString(); profile.Add(DictionaryForProfileItem("dotNetVersion", SULocalizedStrings.StringForKey(".NET Version"), frameworkVersion, frameworkVersion)); // 64-bit? if (Helpers.Is64BitOperatingSystem) { profile.Add(DictionaryForProfileItem("cpu64bit", SULocalizedStrings.StringForKey("CPU is 64-Bit?"), "1", SULocalizedStrings.StringForKey("Yes"))); } else { profile.Add(DictionaryForProfileItem("cpu64bit", SULocalizedStrings.StringForKey("CPU is 64-Bit?"), "0", SULocalizedStrings.StringForKey("No"))); } // CPU Count profile.Add(DictionaryForProfileItem("ncpu", SULocalizedStrings.StringForKey("Number of CPUs"), Environment.ProcessorCount.ToString(), Environment.ProcessorCount.ToString())); // CPU Speed // Use methods other than System.Management when possible, because WMI is both horrendously slow, and // quite prone to deciding to break or completely screw up by itself, it seems. string cpuSpeed; using (var cpuRegistryKey = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0", false)) cpuSpeed = cpuRegistryKey.GetValue("~MHz").ToString(); if (Helpers.StringIsNullOrWhiteSpace(cpuSpeed)) using (var mObj = new System.Management.ManagementObject("Win32_Processor.DeviceID='CPU0'")) cpuSpeed = mObj["CurrentClockSpeed"].ToString(); profile.Add(DictionaryForProfileItem("cpuFreqMHz", SULocalizedStrings.StringForKey("CPU Speed (GHz)"), cpuSpeed.ToString(), (Double.Parse(cpuSpeed) / 1000.0).ToString())); // CPU Type // A problem with this is that Mac OS X and Windows have different values for this; on Windows this is // the processor architecture, and on OS X it is the CPU type. // Windows: http://msdn.microsoft.com/en-us/library/aa394373%28VS.85%29.aspx // OS X: http://www.opensource.apple.com/source/xnu/xnu-1228.12.14/osfmk/mach/machine.h var sysInfo = new NativeMethods.SYSTEM_INFO(); NativeMethods.GetSystemInfoAbstracted(ref sysInfo); int archSparkle = -1; string archDisplay = "Unknown"; switch (sysInfo.wProcessorArchitecture) { case 0: archSparkle = 7; archDisplay = "x86"; break; case 1: archSparkle = 8; archDisplay = "MIPS"; break; case 2: archSparkle = 16; archDisplay = "Alpha"; break; case 3: archSparkle = 3; archDisplay = "PowerPC"; break; case 9: archSparkle = 7; archDisplay = "x86_64"; break; } profile.Add(DictionaryForProfileItem("cputype", SULocalizedStrings.StringForKey("CPU Type"), archSparkle.ToString(), archDisplay)); // CPU Subtype // Until someone wants to write something that will work this out, let's just send the equivalent to // the OS X _ALL. Actually, that's probably accurate, since .NET was designed to be portable. profile.Add(DictionaryForProfileItem("cpusubtype", SULocalizedStrings.StringForKey("CPU Subtype"), "0", "0")); // RAM ulong installedMemory = 0; var memStatus = new NativeMethods.MEMORYSTATUSEX(); if (NativeMethods.GlobalMemoryStatusEx(memStatus)) { installedMemory = memStatus.ullTotalPhys / 1024 / 1024; } profile.Add(DictionaryForProfileItem("ramMB", SULocalizedStrings.StringForKey("Memory (MB)"), installedMemory.ToString(), installedMemory.ToString())); // User preferred language profile.Add(DictionaryForProfileItem("lang", SULocalizedStrings.StringForKey("Preferred Language"), CultureInfo.CurrentCulture.TwoLetterISOLanguageName, CultureInfo.CurrentCulture.TwoLetterISOLanguageName)); return profile; }
/// <summary> /// Will return null if the disk parameters could not be determined. /// </summary> /// <param name="path">An absolute path</param> /// <returns></returns> public static DiskSpaceInfo GetDiskSpaceInfo(string path) { try { string DriveLetter = Path.GetPathRoot(path).TrimEnd(new char[] { '\\' }); System.Management.ManagementObject o = new System.Management.ManagementObject( string.Format("Win32_LogicalDisk.DeviceID=\"{0}\"", DriveLetter)); string fsType = o.Properties["FileSystem"].Value.ToString(); bool isFAT = (fsType == "FAT" || fsType == "FAT32"); UInt64 freeBytes = UInt64.Parse(o.Properties["FreeSpace"].Value.ToString()); UInt64 totalBytes = UInt64.Parse(o.Properties["Size"].Value.ToString()); return new DiskSpaceInfo(freeBytes, totalBytes, isFAT); } catch (Exception exn) { log.Warn(exn, exn); return null; } }
public Logicaldisk(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { if ((path != null)) { if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { throw new System.ArgumentException("Klassenname stimmt nicht überein."); } } PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); curObj = PrivateLateBoundObject; }
/// <summary> /// Obtains information available from FileInfo. /// </summary> /// private void FillDemandInfo() { if (m_IsDisk) { try { //See if this is a network drive //NoRoot = 1 //Removable = 2 //LocalDisk = 3 //Network = 4 //CD = 5 //RAMDrive = 6 System.Management.ManagementObject disk = new System.Management.ManagementObject("win32_logicaldisk.deviceid=\"" + m_Path.Substring(0, 2) + "\""); m_Length = (long)System.Convert.ToUInt64(disk["Size"]);//.ToString().Length; if (System.Convert.ToUInt32(disk["DriveType"]).ToString() == 4.ToString()) { m_IsNetWorkDrive = true; } } catch (Exception) { //Disconnected Network Drives etc. will generate //an error here, just assume that it is a network //drive m_IsNetWorkDrive = true; } finally { m_XtrInfo = true; } } else if (! m_IsDisk && m_IsFileSystem && ! m_IsFolder) { //in this case, it's a file if (File.Exists(m_Path)) { FileInfo fi = new FileInfo(m_Path); m_LastWriteTime = fi.LastWriteTime; m_LastAccessTime = fi.LastAccessTime; m_CreationTime = fi.CreationTime; m_Length = fi.Length; m_XtrInfo = true; } } else { if (m_IsFileSystem && m_IsFolder) { if (Directory.Exists(m_Path)) { DirectoryInfo di = new DirectoryInfo(m_Path); m_LastWriteTime = di.LastWriteTime; m_LastAccessTime = di.LastAccessTime; m_CreationTime = di.CreationTime; m_XtrInfo = true; } } } }
public String GetOSBits() { using (System.Management.ManagementObject mo = new System.Management.ManagementObject("Win32_Processor.DeviceID='CPU0'")) { ushort procArch = (ushort)mo["Architecture"]; if (procArch == 0) { //x86 return "32"; } else if (procArch == 9) { //x64 return "64"; } else if (procArch == 6) { return "ia64"; } return "?"; } }
public override void HandleRequest(string jsonString, AjaxBase ajax) { if (!User.IsAdminLoggedIn(ajax)) { ajax.Unauthorized(); return; } AdminFinderRequest request = Utility.ParseJson<AdminFinderRequest>(jsonString); AdminFinderResponse response = new AdminFinderResponse(); Collection collection = null; string[][] finderData; if (request.cid != -1) { collection = Collection.GetById(request.cid); if (collection == null) { ajax.BadRequest(); return; } finderData = new string[][] { new string[] { collection.Name, collection.Path } }; } else { List<string[]> diskData = new List<string[]>(); string[] discs = Environment.GetLogicalDrives(); for (int i = 0; i < discs.Length; i++) { string driveLetter = discs[i].Replace(":\\", ""); using (System.Management.ManagementObject diskObj = new System.Management.ManagementObject("win32_logicaldisk.deviceid=\"" + driveLetter + ":\"")) { if (diskObj["DriveType"].ToString() == "3") // Local Disk { diskData.Add(new string[] { driveLetter + ":", driveLetter + ":\\" }); } } } finderData = diskData.ToArray(); } Random r = new Random(); StringBuilder tokenBuilder = new StringBuilder(); for (int i = 0; i < 32; i++) { int n = r.Next(36); if (n < 10) { tokenBuilder.Append(n); } else { tokenBuilder.Append(Convert.ToChar(55 + n)); } } response.token = tokenBuilder.ToString(); SessionWrapper.SetFinderData(ajax, response.token, finderData); ajax.ReturnJson(response); }
internal Win32_LogicalDisk(System.Management.ManagementObject mg_object) { _win_logicaldisk = mg_object; }
internal Win32_Service(System.Management.ManagementObject mgo) { _wmi = new WIN32.WmiAccess(); _wmiservice_instance = mgo; }
public Win32_Service(string machineName, string serviceName, string username, string password) { _wmi = new WIN32.WmiAccess(); _wmiservice_instance = WmiAccess.GetInstanceByName(machineName, CLASS_NAME, serviceName); }
public CIM_DataFile(System.Management.ManagementObject cm_mgo) { _cim_file = cm_mgo; }
internal Win32_Process(System.Management.ManagementObject mg_object) { _win_process = mg_object; }
/// <summary> /// Gets total size of the specified disk. /// </summary> /// <param name="disk">The disk to obtain the information for.<param> /// <returns>Returns total size of the specified disk.</returns> public static long GetDiskSize(string disk) { long result = 0; try { string root = System.IO.Path.GetPathRoot(System.IO.Path.GetFullPath(disk)); root = root.Replace(@"\", ""); System.Management.ManagementObject theDisk = new System.Management.ManagementObject("win32_logicaldisk.deviceid=\"" + root + "\""); theDisk.Get(); result = System.Convert.ToInt64(theDisk["Size"]); } catch { } return result; }
internal Win32_DiskDrive(System.Management.ManagementObject mg_object) { _win_diskdrive = mg_object; }
//PHUOCNT TODO: Chưa sử dụng public bool SetPrinterToDefault(string printer) { //path we need for WMI string queryPath = "win32_printer.DeviceId='" + printer + "'"; try { //ManagementObject for doing the retrieval System.Management.ManagementObject managementObj = new System.Management.ManagementObject(queryPath); //ManagementBaseObject which will hold the results of InvokeMethod System.Management.ManagementBaseObject obj = managementObj.InvokeMethod("SetDefaultPrinter", null, null); //if we're null the something went wrong if (obj == null) throw new Exception("Không cho phép chọn máy in mặc định."); //now get the return value and make our decision based on that int result = (int)obj.Properties["ReturnValue"].Value; if (result == 0) return true; else return false; } catch (Exception ex) { //MessageBox.Show(ex.Message); return false; } }