Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you run another .exe from VB.NET as another User?

How do you run another .exe from VB.NET but as another User?

I expect to launch a .exe like "Left Click -> Run As -> Enter User/Pass -> Click OK" If I do that, my application runs as expected (I need to run it as another user to get access to some folders in the network)

But if I use this in VB.NET System.Diagnostics.Process.Start(System.Windows.Forms.Application.ExecutablePath, PARAMETER, USER, PASSWORD, DOMAIN)

The application runs with the other user.. but Excel (inside my App with Interop) fails to open the file in the restricted folder.

(I run again the same app but with a different user, just to avoid creating more .exe files... but I already tried with vbScript)

Again, Process.Start FAILS to open excel using the other User... but Left Click -> Run as succedes at that... why?? another way??

this is what the app does:

  1. Open the app
  2. check if there's a parameter
  3. if no parameter, then relaunch the application with the other user and send some parameter
  4. if there is a parameter open excel
  5. open a xlsx file

but if I double click... Excel opens... uses 50% CPU, and gives me the error that it can't open the file...

if I run it directly with the desired user and pass... everything executes fine Any suggestions as how to solve this? (impersonate works fine.. but it opens Excel with the actual user.. not the one with rights)

Thanks!

like image 445
figus Avatar asked Nov 14 '22 09:11

figus


1 Answers

If you get "Handle is invalid" error, you should try something like this:

dim info As New ProcessStartInfo("...")

info.UseShellExecute = False

info.RedirectStandardInput = True  //This is the key

info.RedirectStandardError = True  //This is the key

info.RedirectStandardOutput = True //This is the key

info.UserName = "username"

info.Password = "password"

Using (install As Process = Process.Start(info))


      Dim output As String = install.StandardOutput.ReadToEnd()

      install.WaitForExit()


End Using

Specifying any one of RedirectStandardOutput=true, RedirectStandardError=true, or RedirectStandardInput=true causes the process to be launched with STARTF_USESTDHANDLES. If your process does not have any of these handles, then CreateProcessWithLogon will fail with "Invalid Handle".

You MUST redirect it (even if you don't intend to write anything to it).

Regards

like image 96
Sebastien Lebreton Avatar answered Dec 25 '22 11:12

Sebastien Lebreton