• 0

[C#] System.Management (Win32_Process)


Question

public void Create(string Name)
        {
            ManagementPath path = new ManagementPath("Win32_Process");
            ManagementClass processClass = new ManagementClass(_mc.Scope, path, null);

            //Gets Path and Executables name.
            string[] splitPath = Name.Split('\\');
            string exeName = splitPath[splitPath.Length - 1];
            string exePath = null;

            ManagementBaseObject inParams = processClass.GetMethodParameters("Create");

            if (splitPath.Length > 1)
                exePath = Name.Substring(0, Name.LastIndexOf('\\'))+"\\";

            //Parameters for creation of process.
            inParams["CommandLine"] = exeName;
            inParams["CurrentDirectory"] = exePath;

            //Invoke Method.
            ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);
            Object returnValue = outParams["ReturnValue"];
            
            switch(int.Parse(returnValue.ToString()))
            {
                case 0: break;
                case 2: throw new System.Security.SecurityException("Access denied");
                case 3: throw new System.Security.SecurityException("Insufficient privilege");
                case 9: throw new Exception(string.Format("Path not found \"{0}\"",exePath));
                case 21: throw new Exception("Invalid parameter");
                default : throw new Exception("Unknown failure");
            }

            //Reload processes.
            getProcesses();
        }

This code is fine for creating processes such as notepad, cmd or calc but as soon as i try and access a path such as "c:\program files\internet explorer\iexplorer.exe" it has a path not found error. Any ideas?

Link to comment
https://www.neowin.net/forum/topic/357162-c-systemmanagement-win32_process/
Share on other sites

15 answers to this question

Recommended Posts

  • 0

Interesting code :)

As for your problem, what occured to me is that "Program Files" has a space in it, but accessing Notepad would access e.g. C:\Windows\Notepad.exe. Is it one of those paths that need to be enclosed with quotes?

  • 0
  Jugalator said:
Interesting code :)

As for your problem, what occured to me is that "Program Files" has a space in it, but accessing Notepad would access e.g. C:\Windows\Notepad.exe. Is it one of those paths that need to be enclosed with quotes?

586359842[/snapback]

Sadly not, I should have said that i've tried that. Still comes up with the same error. Thank you anyway :D

  • 0

You see for your path for internet explorer, try this:

Instead of:

"c:\Program Files\Internet Explorer\IEXPLORE.EXE"

Try the following:

@"c:\Program Files\Internet Explorer\IEXPLORE.EXE"

I know you mentioned you had tried to solve the issues with the spaces in the name, but humour me on this by using the @ symbol at the beginning :)

  • 0

Not that i think this is part of your issue (though it might just make for cleaner, easier to debug code) but can i ask why you didn't use the built-in methods for separating the filename out of a path?

As an example:

string strFullPath = @"c:\program files\internet explorer\iexplore.exe";
string strFileName = System.IO.Path.GetFileName(strFullPath); //  returns "iexplore.exe"
string strPath = System.IO.Path.GetDirectoryName(strFullPath); // returns "c:\program files\internet explorer\"

  • 0
  nowimnothing said:
but can i ask why you didn't use the built-in methods for separating the filename out of a path?

LOL! because i'm abit abstract and don't think things through fully. :happy:

  ramesees said:
You see for your path for internet explorer, try this:

Instead of:

"c:\Program Files\Internet Explorer\IEXPLORE.EXE"

Try the following:

@"c:\Program Files\Internet Explorer\IEXPLORE.EXE"

I know you mentioned you had tried to solve the issues with the spaces in the name, but humour me on this by using the @ symbol at the beginning :)

586360529[/snapback]

Yeah tried this to, usualy i go with "\\" instead of @"\"

For the path i've tried.

"c:\\program files\\Internet Explorer\\"

"\"c:\\program files\\Internet Explorer\\\""

"'c:\\program files\\Internet Explorer\\'"

@"c:\Program Files\Internet Explorer\"

@"'c:\Program Files\Internet Explorer\'"

  benjeeeboy said:
why don't you print out exe path and exe name right before you run the process so you can see what they are coming out as

Tested this to, prints out what it should.

  • 0

Well the path to IE, if it's in a directory called "Program Files" (this depends on the language of Windows) on C:, it should definitely be in @"C:\Program Files\Internet Explorer\iexplore.exe". Case shouldn't matter. Seems to me the problem is something else than the path. :-/

Hmm, here's a guide to WMI and remote process execution in .NET that I found:

http://www.devcity.net/PrintArticle.aspx?ArticleID=144

It's for VB .NET, but consider the API is the same, you'll only have to put up with translating the syntax to C# in your head when reading. :p

  • 0

I have the same problem:

//ConnectionOptions connOption = new ConnectionOptions();

//connOption.Username = "deldom"+@"\"+"deladmin2k";

//connOption.Password = "delhi2k";

//ManagementScope wmiScope = new ManagementScope(@"\\xpbuild",connOption);

ManagementScope wmiScope = new ManagementScope(@"\\xpbuild");

wmiScope.Connect();

ManagementClass process = new ManagementClass("Win32_Process");

process.Scope = wmiScope;

ManagementBaseObject inParams = process.GetMethodParameters("Create");

inParams["CommandLine"] = command + " " + argStr;

//inParams["CommandLine"] = @"C:\WINNT\NOTEPAD.EXE";

ManagementBaseObject outParams = process.InvokeMethod("Create", inParams, null);

err.Append("Command " + command);

err.Append("Argument " + argStr);

err.Append("returnValue = " + outParams["ReturnValue"]);

err.Append("Process ID = " + outParams["processId"]);

resultString = err.ToString();

- - - my result string always comes back with return value "3" ...

command = C:\Inetpub\wwwroot\BESAdmin\bin\BESUserAdminClient.exe

argStr = -set_password test -b XYZServer02 -u BlackBerryUser1@XYZServer02.na.usauser -n xyzserver03 -p Password123

ph8l: did you fixed this issue.

this same command i am able to use without any issue.

Edited by avasi
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Apple don't care. These kind of ads always look worse for the advertiser doing the mocking. It took Samsung years to stop it. Apple barely got away with it in the Mac/PC ads back in the day.
    • I just wish iOS handled MDM the same as Android. A separate closed off section that I can turn off on the weekends and holiday.
    • But what does Everything bring if you're not interested in search, but browsing files and directories in the classic file explorer sense? It's not always you're interested in searching for something in particular.
    • NWinfo 1.4.2 by Razvan Serea NWinfo is a lightweight tool designed to give a quick look at your computer's key details, from hardware to software specs, without any fuss. You don't need to install it; just download, run, and see everything you need on one screen. It displays essential info about your CPU, memory, disk drives, network, and even the system's operating details. Since it’s portable, you can carry NWinfo on a USB stick and use it on any Windows machine, making it a handy tool for both tech enthusiasts and troubleshooting. NWinfo key features: Lightweight and portable—no installation required Simple, user-friendly interface for easy navigation Displays detailed CPU information, including model and speed Shows memory (RAM) specifications and usage Provides disk information, including storage capacity and usage Lists network adapters and IP addresses Displays motherboard details, including model and manufacturer Shows system uptime and operating system version Detects graphics card information and driver details Includes battery status for laptops Provides monitor specifications, including resolution and refresh rate Displays BIOS version and other firmware details Offers a summary of active processes and services Generates detailed logs for sharing or troubleshooting Open-source and free, allowing for customization and community support NWinfo 1.4.2 changelog: Add Polish language support Add support for EFI key options Refactor EFI boot menu enumeration Add FACS table parsing Add SMBIOS support for types 37-39 and 42 Note: NWinfo might trigger a few antivirus alerts or show up with warnings on VirusTotal due to its low download frequency. If you have any concerns, you're welcome to review the full source code available on the developer’s repository. Download: NWinfo 1.4.2 | 2.2 MB (Open Source) View: NWinfo Website | NWinfo@GitHub | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      Zojaji earned a badge
      Week One Done
    • First Post
      Soeaker4thedead earned a badge
      First Post
    • First Post
      kryptickid earned a badge
      First Post
    • First Post
      Nemesis-IV earned a badge
      First Post
    • First Post
      Aidan Helfrich earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      759
    2. 2
      ATLien_0
      187
    3. 3
      +FloatingFatMan
      151
    4. 4
      Xenon
      117
    5. 5
      wakjak
      113
  • Tell a friend

    Love Neowin? Tell a friend!