How to retrieve executable program path remotely - c#

I'm writing a program that needs to get the install date and version information of all the programs in a registry. I am able to get a list of all of the programs, but I do not know how to access any information about the programs themselves. If I was able to determine the filepath to where the files are located I would be able to access this information. I happen to know that the programs I'm interested in are all located in the C:\\Program Files (x86)\ folder, but they are in subfolders within this that I am unable to specify. Any ideas on how to get the filepaths of the files I am retrieving?
Here's my code:
public List<BSAApp> getInstalledApps( string computerName )
{
List<BSAApp> appList = new List<BSAApp>();
ManagementScope ms = new ManagementScope();
ms.Path.Server = computerName;
ms.Path.NamespacePath = "root\\cimv2";
ms.Options.EnablePrivileges = true;
ms.Connect();
ManagementClass mc = new ManagementClass( "StdRegProv" );
mc.Scope = ms;
ManagementBaseObject mbo;
mbo = mc.GetMethodParameters( "EnumKey" );
mbo.SetPropertyValue( "sSubKeyName", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths" );
string[] subkeys = (string[])mc.InvokeMethod( "EnumKey", mbo, null ).Properties["sNames"].Value;
if( subkeys != null )
{
foreach( string strKey in subkeys )
{
string path = ?????
FileVersionInfo info = FileVersionInfo.GetVersionInfo( path );
appList.Add( new BSAApp( strKey, info.ProductVersion ) );
}
}
return appList;
}

ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Product");
foreach(ManagementObject mo in mos.Get())
{
Console.WriteLine(mo["Name"]);
Console.WriteLine(mo["InstallState"]);
}
Get installed applications in a system
But as mentioned in that thread, it has its own drawbacks.

Related

Getting the name of the installed program, its version and installation date WMI C#

I'm trying to get information about the programs installed on remote devices. At the moment, I found a way to output all installed programs. Is there a way to get the version and date of installation?
List<string> programs = new List<string>();
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.Username = "USERNAME";
connectionOptions.Password = "USERPASS";
//connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
string devicename = textBox8.Text;
ManagementScope scope = new ManagementScope("\\\\" + devicename + "\\root\\CIMV2", connectionOptions);
scope.Connect();
string softwareRegLoc = #"Software\Microsoft\Windows\CurrentVersion\Uninstall";
ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);
ManagementBaseObject inParams = registry.GetMethodParameters("EnumKey");
inParams["hDefKey"] = 0x80000002;//HKEY_LOCAL_MACHINE
inParams["sSubKeyName"] = softwareRegLoc;
// Read Registry Key Names
ManagementBaseObject outParams = registry.InvokeMethod("EnumKey", inParams, null);
string[] programGuids = outParams["sNames"] as string[];
foreach (string subKeyName in programGuids)
{
inParams = registry.GetMethodParameters("GetStringValue");
inParams["hDefKey"] = 0x80000002;//HKEY_LOCAL_MACHINE
inParams["sSubKeyName"] = softwareRegLoc + #"\" + subKeyName;
inParams["sValueName"] = "DisplayName";
// Read Registry Value
outParams = registry.InvokeMethod("GetStringValue", inParams, null);
if (outParams.Properties["sValue"].Value != null)
{
string softwareName = outParams.Properties["sValue"].Value.ToString();
programs.Add(softwareName);
}
}
foreach (string softwareName in programs)
{
int n = dataGridView8.Rows.Add();
dataGridView8.Rows[n].DefaultCellStyle.BackColor = Color.LightGreen;
dataGridView8.Rows[n].Cells[0].Value = devicename;
dataGridView8.Rows[n].Cells[1].Value = softwareName;
dataGridView8.FirstDisplayedScrollingRowIndex = dataGridView8.RowCount - 1;
}
}
catch
{
MessageBox.Show("Something went wrong");
}
}
Welcome to Stack Overflow. Use ORMi library to get that information easily:
1) Install via NuGet:
Install-Package ORMi
2) Use the library:
using ORMi;
3) Instanciate and use:
WMIHelper helper = new WMIHelper("root\CimV2");
var programs = helper.Query("SELECT Name, Version, InstallDate FROM Win32_Product").ToList();
foreach(var p in programs)
{
Console.WriteLine(p.Name);
}
And that´s it. Then if you want to do some more advanced working you can define your model classes and query in a simpler way. You can read the docs on GitHub.

write protection mode will not change

I use this following code to remove the write protection folder so that I can delete that. But It won't work.
File.SetAttributes(#"F:\File", FileAttributes.Normal);
File.Delete(#"F:\File");
How can I remove the write protection?
If I can remove file protection from the disk, so give some codes to do that.
Any help will be appreciated
Thanks in advance
There is a difference between Folder and File. With this you will remove the readonly atribute and delete the folder.
var di = new DirectoryInfo(#"F:\File");
di.Attributes &= ~FileAttributes.ReadOnly;
di.Delete(true);
EDIT:
Formating USB drive. You can read the article.
public static bool FormatDrive(string driveLetter,
string fileSystem = "NTFS", bool quickFormat=true,
int clusterSize = 8192, string label = "", bool enableCompression = false )
{
if (driveLetter.Length != 2 || driveLetter[1] != ':'|| !char.IsLetter(driveLetter[0]))
return false;
//query and format given drive
ManagementObjectSearcher searcher = new ManagementObjectSearcher
(#"select * from Win32_Volume WHERE DriveLetter = '" + driveLetter + "'");
foreach (ManagementObject vi in searcher.Get())
{
vi.InvokeMethod("Format", new object[]
{ fileSystem, quickFormat,clusterSize, label, enableCompression });
}
return true;
}
You should put the driveLetter like this: "F:"

Creating and deleting files on remote machine

I want to create and delete a file on a remote machine of which i have admin username and password.
I am using this code
ConnectionOptions options = new ConnectionOptions();
options.Username = "admin";
options.Password = "12345";
ManagementScope scope = null;
ObjectQuery query = null;
ManagementObjectSearcher searcher = null;
try
{
scope = new ManagementScope(#"\\192.168.3.125\root\CIMV2", options);
scope.Connect();
query = new ObjectQuery(#"SELECT * FROM CIM_Datafile WHERE name = 'c:\\c$\\Testing\\Test.txt'");
searcher = new ManagementObjectSearcher(scope, query); // EDIT forgot to include 'scope' previously
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
foreach(ManagementObject mo in searcher.Get())
{
uint returnCode = (uint)mo.InvokeMethod("Delete", null);
if (returnCode == 0)
Console.WriteLine("File was successfully deleted");
else
Console.WriteLine("Deletion failed due to return code " + returnCode);
}
But it is giving me invalid query error and also i want to know how to Create a file on Remote machine.
and i even cant access the path \\192.168.3.125\C$\Testing\Test.txt
My file location is c:\Testing\Test.txt
Firstly can you access the file via the windows explorer from the machine (start -> run -> \192.168.3.125\C$\Testing\Test.txt)
If so what's wrong with
File.Delete(#"\\192.168.3.125\C$\Testing\Test.txt");
In my case, when I was connecting two windows based computers, you could just put:
#"\\PC-NAME\NEXT-FOLDER\NEXT-FOLDER\test.txt"

Where can I get info about notebook's model name?

I trying to get info about HW from notebooks. I do this via WMI, but not always there contains the info about notebook model for example. It depends on the manufacturer, SONY never contains HW info in WMI.
FileStream fs = new FileStream(#"C:\log.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs);
string[] Names = { "Win32_Fan", "Win32_HeatPipe", "Win32_Refrigeration", "Win32_TemperatureProbe", "Win32_Keyboard", "Win32_PointingDevice",
"Win32_AutochkSetting", "Win32_CDROMDrive" , "Win32_DiskDrive" ,"Win32_FloppyDrive", "Win32_PhysicalMedia","Win32_TapeDrive" ,
"Win32_1394Controller","Win32_1394ControllerDevice", "Win32_AllocatedResource", "Win32_AssociatedProcessorMemory","Win32_BaseBoard",
"Win32_BIOS", "Win32_Bus","Win32_CacheMemory","Win32_ControllerHasHub","Win32_DeviceBus","Win32_DeviceMemoryAddress", "Win32_DeviceSettings",
"Win32_DMAChannel","Win32_FloppyController","Win32_IDEController","Win32_IDEControllerDevice","Win32_InfraredDevice","Win32_IRQResource","Win32_MemoryArray",
"Win32_MemoryArrayLocation","Win32_MemoryDevice","Win32_MemoryDeviceArray","Win32_MemoryDeviceLocation","Win32_MotherboardDevice","Win32_OnBoardDevice",
"Win32_ParallelPort","Win32_PCMCIAController","Win32_PhysicalMemory","Win32_PhysicalMemoryArray","Win32_PhysicalMemoryLocation","Win32_PNPAllocatedResource",
"Win32_PNPDevice","Win32_PNPEntity","Win32_PortConnector","Win32_PortResource","Win32_Processor","Win32_SCSIController", "Win32_SCSIControllerDevice","Win32_SerialPort",
"Win32_SerialPortConfiguration","Win32_SerialPortSetting","Win32_SMBIOSMemory","Win32_SoundDevice","Win32_SystemBIOS","Win32_SystemDriverPNPEntity","Win32_SystemEnclosure",
"Win32_SystemMemoryResource","Win32_SystemSlot","Win32_USBController","Win32_USBControllerDevice","Win32_USBHub","Win32_NetworkAdapter",
"Win32_NetworkAdapterConfiguration","Win32_NetworkAdapterSetting","Win32_Battery","Win32_CurrentProbe","Win32_PortableBattery",
"Win32_PowerManagementEvent","Win32_VoltageProbe","Win32_DriverForDevice","Win32_Printer","Win32_PrinterConfiguration","Win32_PrinterController",
"Win32_PrinterDriver","Win32_PrinterDriverDll","Win32_PrinterSetting","Win32_PrintJob","Win32_TCPIPPrinterPort","Win32_POTSModem","Win32_POTSModemToSerialPort",
"Win32_DesktopMonitor","Win32_DisplayConfiguration","Win32_DisplayControllerConfiguration","Win32_VideoConfiguration","Win32_VideoController","Win32_VideoSettings"};
foreach (string name in Names)
{
sw.WriteLine(" ");
sw.WriteLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
sw.WriteLine(name);
sw.WriteLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM " + name);
ManagementObjectCollection information = searcher.Get();
foreach (ManagementObject obj in information)
{
foreach (PropertyData data in obj.Properties)
{
sw.WriteLine("{0} = {1}", data.Name, data.Value);
}
}
}
sw.Close();
Where can I get this info?
Thanks!
You could try getting this information from the BIOS information, which is stored in the registry under the HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\BIOS. It should be in the SystemProductName or SystemVersion value.
Model and serial number contain in the "Win32_ComputerSystemProduct".

Get a list of all UNC shared folders on a local network server

I'm trying to get a list of all shared folders available on a local intranet server.
The System.IO.Directory.GetDirectories() works fine for a path like \\myServer\myShare, however I'm getting an exception for a path like \\myServer:
Unhandled Exception: System.ArgumentException: The UNC path should be of the form \server\share.
Is there a way to get a list all shared folders for a server? Ultimately I'm looking for a method that can handle both scenarios based on a given path - returning a list of all shares for a given server and returning a list of all subdirectories for a given network shared folder.
Here's a technique that uses System.Management (add a reference to this assembly):
using (ManagementClass shares = new ManagementClass(#"\\NameOfTheRemoteComputer\root\cimv2", "Win32_Share", new ObjectGetOptions())) {
foreach (ManagementObject share in shares.GetInstances()) {
Console.WriteLine(share["Name"]);
}
}
Appropriate permissions are required.
I think this is what you are looking for http://www.codeproject.com/KB/IP/networkshares.aspx
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"];
// Full Access = 2032127, Modify = 1245631, Read Write = 118009, Read Only = 1179817
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;
}

Categories