Executing batch file from c# silently - c#

I know this question has been asked previously and I have tried all the solutions given in those posts before but I can't seem to make it work:-
static void CallBatch(string path)
{
int ExitCode;
Process myProcess;
ProcessStartInfo ProcessInfo;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/c " + path);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = true;
myProcess = Process.Start(ProcessInfo);
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.WaitForExit();
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(process_Exited);
ExitCode = myProcess.ExitCode;
Console.WriteLine("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
myProcess.Close();
}
When I try to call the batch file, it still shows the window even though createNoWindow and UseShellExecute are both set to true.
Should I put something else to make it run the batch file silently?

Try this:
Process myProcess = new Process();
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = "cmd.exe";
myProcess.StartInfo.Arguments = "/c " + path;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(process_Exited);
myProcess.Start();
myProcess.WaitForExit();
ExitCode = myProcess.ExitCode;
The idea is to not manipulate myProcess.StartInfo after you have started your process: it is useless. Also you do not need to set UseShellExecute to true, because you are starting the shell yourself by calling cmd.exe.

Related

C# implicitly calls the CMD command Attrib with administrator privileges

Use C# to copy WINDOWS log files to other disks. The main problem is that the CMD command with administrator privileges will not be called, and some of the things mentioned on the Internet will not work.
private Process proc = null;
public Command()
{
proc = new Process();
}
public void RunCmd(string cmd)
{
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = "C:\Windows\System32\cmd.exe";
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.Verb = "RunAs";
proc.Start();
proc.StandardInput.WriteLine(cmd);
proc.Close();
}
public void ChangeFile(string path1,string path2)
{
Command cmd = new Command();
cmd.RunCmd("attrib -s" + " " + path1);
Directory.CreateDirectory(path2);
cmd.RunCmd("Xcopy" + " " + path1 + " " + path2);
}
Hope someone can tell me how to fix it.
You can restart a process as an administrator like this:
ProcessStartInfo info = new ProcessStartInfo(#"C:\Windows\cmd.exe");
info.UseShellExecute = true;
info.Verb = "runas";
Process.Start(info);
For details, please refer to Run process as administrator from a non-admin application

Create a process that execute powershell in C# but failed outpt

I dont know where is my missing. Even it dit not write out log. Could you fix my test code:
private void button1_Click(object sender, EventArgs e)
{
try
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = #"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
startInfo.Arguments = #"/C Import-Module AppLocker;Set-AppLockerPolicy -XMLPolicy 'iPolicy.xml' > C:\log.txt";
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
//startInfo.RedirectStandardOutput = true;
//startInfo.RedirectStandardError = true;
//startInfo.UseShellExecute = false;
//startInfo.CreateNoWindow = false;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
}
catch (Exception ex) {
Debug.Print("Error: " + ex.Message);
}
}
Finally got it to work, code should look like this:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = #"cmd.exe";
startInfo.Arguments = #"/C powershell.exe /C Import-Module AppLocker;Set-AppLockerPolicy -XMLPolicy 'iPolicy.xml' > C:\log.txt";
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
This worked for me! You can use full paths to cmd.exe and powershell.exe if you feel necessary, it's not that important here.

Problems using cmd with unity

I'm trying to run command prompt from unity, my problem is that I can't find a way to fetch the result, here's my code
Process myProcess = new Process();
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.FileName = "C:\\Windows\\system32\\cmd.exe";
string path = "C:\\Users\\Sam\\Desktop\\Test\\rubik3Sticker.generator";
myProcess.StartInfo.Arguments = "call " + path;
myProcess.EnableRaisingEvents = true;
myProcess.Start();
until here it gives no exceptions, but unity crashes when I try to add this:
while(!myProcess.StandardOutput.EndOfStream)
print(myProcess.StandardOutput.ReadLine());
any kind of help would be appreciated, thanks!

How to hide cmd window while running a batch file?

How to hide cmd window while running a batch file?
I use the following code to run batch file
process = new Process();
process.StartInfo.FileName = batchFilePath;
process.Start();
If proc.StartInfo.UseShellExecute is false, then you are launching the process and can use:
proc.StartInfo.CreateNoWindow = true;
If proc.StartInfo.UseShellExecute is true, then the OS is launching the process and you have to provide a "hint" to the process via:
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
However the called application may ignore this latter request.
If using UseShellExecute = false, you might want to consider redirecting standard output/error, to capture any logging produced:
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
proc.StartInfo.RedirectStandardError = true;
proc.ErrorDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
And have a function like
private void ProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data)) // use the output outLine.Data somehow;
}
There's a good page covering CreateNoWindow this on an MSDN blog.
There is also a bug in Windows which may throw a dialog and defeat CreateNoWindow if you are passing a username/password. For details
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98476
http://support.microsoft.com/?kbid=818858
According to the Process properties, you do have a:
Property: CreateNoWindow
Notes: Allows you to run a command line program silently.
It does not flash a console window.
and:
Property: WindowStyle
Notes: Use this to set windows as hidden.
The author has used ProcessWindowStyle.Hidden often.
As an example!
static void LaunchCommandLineApp()
{
// For the example
const string ex1 = "C:\\";
const string ex2 = "C:\\Dir";
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = "dcm2jpg.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch
{
// Log error.
}
}
Use:
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
This is what worked for me,
When you redirect all of the input and output, and set the window hidden it should work
Process p = new Process();
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
try with this and this where the c# code is embedded into the batch files:
#echo off
echo self minimizing
call getCmdPid.bat
call windowMode.bat -pid %errorlevel% -mode minimized
echo --other commands--
pause
Though it might be not so easy to unhide the window.

Process.Exited event is not be called

I have the following code snippet to call into command line:
p = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "cmd.exe";
psi.Arguments = "/C " + "type " + “[abc].pdf”;
psi.UseShellExecute = false;
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.CreateNoWindow = true;
p.StartInfo = psi;
p.EnableRaisingEvents = true;
p.Exited += new EventHandler(p_Exited);
p.Start();
p.WaitForExit();
Strangely, When [abc] is a small pdf file(8kb) p_Exited is called. But when it's a large pdf file(120kb) it is never called. Any clues?
Thanks,
You need to consume the output stream when the standard output has been redirected:
p.Start();
p.StandardOutput.ReadToEnd();
p.WaitForExit();

Categories