calling devcon from inside windows forms not working

1.1k views Asked by At

Plan

The plan is to disable and subsequently enable a device from inside a windows forms application. To test the first building block of my plan, I open cmd with admin privileges and the following works perfectly:

> devcon hwids =ports
> devcon hwids *VID_10C4*
> devcon disable *VID_10C4*
> devcon enable *VID_10C4*

I can see the device being disabled and enabled again in device manager.

I can also achieve all of this by putting the commands into a batch file and running it from cmd with admin privileges. The above tells me that my plan is essentially good.

Application

However, what I actually want to do is achieve the same thing from inside a windows forms application:

  1. I've set the following in the app manifest:

    requestedExecutionLevel level="requireAdministrator" uiAccess="false"

  2. For the sake of baby steps, I have checked this, just to ensure that there are no stupid mistakes in paths and whatnot. And it works just fine. The log file shows me the expected output from the dir command.

         // Build String 
             string strCmdText =
             "'/c cd " + prodPath +
             " && dir " +
             " > logs\\logFileEnablePrt.txt \"'";
    
    
         // Run command 
             var p = new System.Diagnostics.Process();
             var psi = new ProcessStartInfo("CMD.exe", strCmdText);
             psi.Verb = "runas"; // admin rights
             p.StartInfo = psi;
             p.Start();
             p.WaitForExit();
    
  3. However, this does not work. It always returns an empty log file and does not change the device as expected:

         // Build String 
             string strCmdText =
             "'/c cd " + prodPath +
             " && devcon hwids =ports " +
             " > logs\\logFileEnablePrt.txt \"'";
    
    
         // Run command 
             var p = new System.Diagnostics.Process();
             var psi = new ProcessStartInfo("CMD.exe", strCmdText);
             psi.Verb = "runas"; // admin rights
             p.StartInfo = psi;
             p.Start();
             p.WaitForExit();
    

Error from cmd window is :

'devcon' is not recognized as an internal or external command,

operable program or batch file.

What's going on?

The above has me stumped. I've proved the commands work. I've proved my C# code works. But when I join the 2 together, it doesn't work...

NB: My C# program is running on my D: drive, if that makes any difference...

Updates Based on Comments

@Compo Using your code, it does exactly the same as with mine. I see an empty log file & no changes made to the device. I've altered the /c to /k so I can see what going on the cmd terminal and I see this:

enter image description here

I've even tried your code C:\\Windows\\System32\\devcon hwids =usb pointing directly at devcon. Also tried \devcon.exe for completeness. The inexplicable error is :

enter image description here

I can see the flipping devcon.exe file sitting right there in the folder! Is there any reason it would not recognise it?

Also, with the command as you wrote it, the log file name is actually named logFileEnablePrt.txt'. I agree that your command looks right, so don't ask me why this happens!

enter image description here

@Panagiotis Kanavos using your code, I get the following error:

enter image description here

This is at the line p.Start();. I tried putting in devcon.exe, and even the whole path (I checked the folder was in my PATH, and it is). Can't get past this. I actually stumbled on that answer you shared and arrived at this brick wall already.

3

There are 3 answers

5
shingo On

Here is the code works for me, I don't have ports devices so I change it to usb.

public static void Main()
{
    string prodPath = @"c:\devcon\x64";

    // Build String 
    string strCmdText =
    "/c \"cd /d " + prodPath +
    " && devcon hwids =usb " +
    " > log.txt \"";

    // Run command 
    var p = new Process();
    var psi = new ProcessStartInfo("CMD.exe", strCmdText);
    psi.Verb = "runas"; // admin rights
    p.StartInfo = psi;
    p.Start();
    p.WaitForExit();
}
1
Shovers_ On

Worked through a few steps and think I may have an answer...[1]

Just specifying devcon fails as expected...windows cant find the exe as the folder it is in is not in the %PATH% variable in windows..

IF I specify the full path however it works... enter image description here

It wasnt clear from your original code but if your copy of devcon is sitting in either System32 or Syswow directories you may be hitting an emulation issue as well...see here....

EDIT1:: A way to prove this would be to do Direcory.GetFiles(directory containing devcon) and see if the results line up with what you expect

As for passing arguments through to devcon I'd try something like this as opposed to trying to concatenate one giant cmd line..

enter image description here

A similar example but with netstat:

enter image description here

EDIT 2::Another example but with devcon: enter image description here enter image description here enter image description here

The target platform here for the build was x64

EDIT3:: With my application build set to x86:

enter image description here

0
monkey On

After working through the answers and comments above, I seem to have something that reliably works, which obviously I'd like to share back for scrutiny and future use.

So, my function ended up looking like this:

    private int enablePort(string action)
    {
        while (true)
        {

        // Command Arg
            string devconPath = @"c:\Windows\SysNative";
            string strCmdText =
                "'/c \"cd /d \"" + 
                devconPath +
                "\" && c:\\Windows\\SysNative\\devcon " + action + " *VID_10C4* " +
                "> \"" + prodPath + "\\logs\\logFileEnablePrt.txt\"\"";

        // Process
            var p   = new Process();
            var psi = new ProcessStartInfo()
            {
                Arguments = strCmdText,
                Verb = "runas",
                FileName = "CMD.exe",
                UseShellExecute = true
            };
            p.StartInfo = psi;
            p.Start();
            p.WaitForExit();


                
        // Grab log output
            string logPath = prodPath + "\\logs\\logFileEnablePrt.txt";
            Console.WriteLine("logPath = " + logPath);
            string tempFile = System.IO.File.ReadAllText(logPath);
            System.Console.WriteLine("Contents of WriteText.txt = \n{0}", tempFile);


        // Check if it worked
            var success = false;
            if (tempFile.Contains(action))
            {
                success = true;
                return 0;
            }

            // Error  ->  Allow user to try again!
            if (MessageBox.Show("Was unable to " + action + " Test Jig COM port. Unlug & Replug USB. Check COM port is enabled if not working.", "COM Port Problem", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return -1;
            }
        }
    }

And the calling code was:

        this.enablePort("disable");
        int milliseconds = 3000;
        await Task.Delay(milliseconds);
        this.enablePort("enable");

As you can see in the code above, I've logged everything to see what was going on... Stepping through with the debugger, I can now see after the disable:

USB\VID_10C4&PID_EA60\0001 : Disabled 1 device(s) disabled.

And then after the enable:

USB\VID_10C4&PID_EA60\0001 : Enabled 1 device(s) are enabled.

The one extra thing I need to stress is that during testing, I thought I could hook a serial peripheral onto the port and determine whether it could disable and enable successfully by checking the connection. THIS DOES NOT WORK. The above code only works when the port is idle. Perhaps someone who understands the underlying software could hazard an explanation of why this is.