Reputation: 131
I have a bat file that copies files from one location to another.
SET SRC=%1
SET DEST=%2
xcopy /Y/I %SRC%\*.txt %DEST%\temp
echo Done!
I'm trying to run this file via 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 executed, I can see the 'Done!' message in the output, but files are not copied.
The only way it works is
psi.UseShellExecute = true;
psi.RedirectStandardOutput = false;
psi.RedirectStandardError = false;
But in this case I have to disable output/error redirection and I need them. So this doesn't work for me.
I have tried to set administrator's username/password
psi.UserName = username;
psi.Password = password;
Logon succeed, but I get the 'The handle is invalid' message in the StandardError Stream.
I guess the process I'm trying to run doesn't have permissions to copy files and I don't know how to grant him these permissions.
Please, help!
EDITED
Thank you for replies! I have spend several hours trying to handle this issue and as it always happens I have posted my question and found the solution :)
In order to avoid getting 'The handle is invalid' message you have to
psi.RedirectStandardInput = true;
But now I can see cmd.exe window, if UserName is set, which is bad.
Upvotes: 4
Views: 2919
Reputation: 2079
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 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);
}
Upvotes: 1