How to run bat file with necessary permissions in C #

I have a bat file that copies files from one place to another.

SET SRC=%1 SET DEST=%2 xcopy /Y/I %SRC%\*.txt %DEST%\temp echo Done! 

I am trying to run this file through a C # program

 var psi = new ProcessStartInfo(fileToRun); psi.Arguments = args; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.WindowStyle = ProcessWindowStyle.Hidden; psi.UseShellExecute = false; psi.CreateNoWindow = true; Process cmdProc = Process.Start(psi); StreamReader output = cmdProc.StandardOutput; StreamReader errors = cmdProc.StandardError; cmdProc.WaitForExit(); 

Bat file is running, I see the message "Finish!" output, but files are not copied.

The only way this works is

 psi.UseShellExecute = true; psi.RedirectStandardOutput = false; psi.RedirectStandardError = false; 

But in this case, I need to disable output / error redirection, and I need them. So this does not work for me.

I tried to set admin username / password

 psi.UserName = username; psi.Password = password; 

Login successfully completed, but I get an "Invalid handle descriptor in a StandardError stream.

I assume that the process I'm trying to start does not have permission to copy files, and I don’t know how to grant it these permissions.

Please, help!

EDITED

Thanks for answers! I spent several hours to deal with this problem, and, as always, I posted my question and found a solution :)

To avoid the "Invalid handle" message, you should

 psi.RedirectStandardInput = true; 

But now I see the cmd.exe window if UserName is set, which is bad.

+4
source share
1 answer

you are missing

 psi.Domain = "domain"; psi.Verb ="runas"; //if you are using local user account then you need supply your machine name for domain 

try this simple snippet that should work for you

 void Main() { string batchFilePathName =@ "drive:\folder\filename.bat"; ProcessStartInfo psi = new ProcessStartInfo(batchFilePathName); psi.Arguments = "arg1 arg2";//if any psi.WindowStyle = ProcessWindowStyle.Hidden; psi.UseShellExecute = false; psi.Verb ="runas"; psi.UserName = "UserName"; //domain\username psi.Domain = "domain"; //domain\username //if you are using local user account then you need supply your machine name for domain psi.WindowStyle = ProcessWindowStyle.Hidden; psi.UseShellExecute = false; psi.Verb ="runas"; Process ps = new Process(psi); Process.Start(ps); } 
+1
source

Source: https://habr.com/ru/post/1392189/


All Articles