Problem with running batch files from within my application - c#

I've been trying to create a simple application to backup my Windows Server databases aswell as a whole server backup.
For this I want to use batch files which are being executed by my application.
I tried several approaches but for some reason it always fails so I'd be happy if you could help me out.
Batch file BACKUPSERVER:
wbadmin start backup -backupTarget:D: -include:C: -allCritical -quiet
I have to run the bat as administrator or it fails due to missing permissions.
C# code:
static Task<int> RunProcessAsync(string fileName)
{
............
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.Verb = "runas";
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C \"D:\\SQLBACKUP\\BACKUPSERVER.bat\"";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
Debugging says 'wbadmin wasnt found'. 'runas' activated or not doesn't make any difference.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = fileName;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = true;
startInfo.CreateNoWindow = false;
// startInfo.Verb = "runas";
var process = new Process
{
StartInfo = { FileName = fileName },
EnableRaisingEvents = true
};
process.StartInfo = startInfo;
process.Exited += (sender, args) =>
{
tcs.SetResult(process.ExitCode);
process.Dispose();
};
process.Start();
Also doesn't work.
Any ideas?
EDIT:
I'm able to run commands like shutdown but wbadmin doesn't work whatsoever...

This is how I solved the problem:
Make sure ure compiling for 64bit if u intend to use your application on 64bit system, otherwise it will redirect to different subfolders and wont find 'wbadmin.exe'.
Run wbadmin with ProcessStart or run a batch but without direct cmd input, so use this with filename = batch file or wbadmin with startInfo.Arguments:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = fileName;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = true;
startInfo.CreateNoWindow = false;
// startInfo.Verb = "runas";
var process = new Process
{
StartInfo = { FileName = fileName },
EnableRaisingEvents = true
};
process.StartInfo = startInfo;
process.Exited += (sender, args) =>
{
tcs.SetResult(process.ExitCode);
process.Dispose();
};
process.Start();
Make sure u request administrator rights

Related

Command hanging in C# when running Postman's Newman command

I'm trying to use cmd CLI to excute a newman collection run. However when the process is running it's getting stuck and never finishes processing.
Any suggestions on how to deal with that?
string cmdCommand="newman run demo.postman_collection.json --env-var HTTP_PROXY --insecure";
int TotalTimeout= 150000;
CliProcess = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new
System.Diagnostics.ProcessStartInfo();
if (_inputDir != null)
{
startInfo.WorkingDirectory = _inputDir;
}
//startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.CreateNoWindow = false;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C "+cmdCommand;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
bool processExited;
startInfo.RedirectStandardOutput = false;
CliProcess.StartInfo = startInfo;
CliProcess.Start();
CliProcess.StandardInput.WriteLine("exit");
//CliProcess.BeginOutputReadLine();
//CliProcess.BeginErrorReadLine();
//CliProcess.Close();
processExited = CliProcess.WaitForExit(TotalTimeout);
// //&& outputWaitHandle.WaitOne(TotalTimeout) && errorWaitHandle.WaitOne(TotalTimeout);
//CliProcess.CancelOutputRead();
//CliProcess.CancelErrorRead();
//ExitCode = GetProcessExitCode();
//CliProcess.Kill();
//}
//Wait additional minute for the process to exit
if (!processExited)
{
KillNewman();
TraceLogger.Instance.LogMessage(TraceLevel.Warning, MsgSrc, "[SendCmdCommand(string cmdCommand)] Newman process was killed due to timeout");
}
This is the most I can get out of it:
It gets stuck here^ and never continues.
the problem was due to the fact that the proxy was misconfigured so the request was sent trying to get to an unresponsive proxy server...
So in conclusion, there was nothing wrong with the code itself.

Run a C# exe with parameters that is to start another application and get output from console

I have an exe which has some parameters- path of another application and some files to be opened from that application. There would be an output as part of that application which would be displayed in the console of my exe.
But i am unable to get the output from the console.
I have the code:
ProcessStartInfo psi = new ProcessStartInfo("\"" + dllpath + "\\newapplication.exe" + "\"");
Process p = new Process();
psi.UseShellExecute = false;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
p.Start();
The process starts successfully, and then i have to open a file in the process which happens through another class. So after the file opened, some extraction happens and the result is displayed on the console.
When i give p.WaitForExit(); nothing happens other than starting the application! How do i acheive to retreive the output on StandardOutput as per my code? Need Help!
This is the correct way to do it:
string outputProcess = "";
string errorProcess = "";
using (Process process = new Process())
{
process.StartInfo.FileName = path;
process.StartInfo.Arguments = arguments;
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
outputProcess = process.StandardOutput.ReadToEnd();
errorProcess = process.StandardError.ReadToEnd();
process.WaitForExit();
}
Remember to use the using statement when you have an IDisposable object

running cmd in c# answer yes to prompt

I'm running the below command from c#. There is a prompt that will be shown that I want to answer "yes" to how can I do this with the current code
If I run this as a batch script I can just do
echo y | pscp.exe -batch -pw password E:\\Certs\\client.conf me#<ip>:/home/user
which works - but unsure how I can replicate this using the below
string pscpPath="-batch -pw password E:\\Certs\\client.conf me#<ip>:/home/user";
ExecuteCopyCerts("pscp.exe", pscpPath);
Function:
public Boolean ExecuteCopyCerts(string fileName, string arguments)
{
txtLiveHubStatus.Text = "";
try
{
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo(fileName, arguments);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
return proc.ExitCode == 0;
}
}
Set RedirectStandardInput to true
procStartInfo.RedirectStandardInput = true
and then write to StandardInput
proc.StandardInput.WriteLine("yes");
To reiterate what Hesam said though the prompt is Y, not yes. This is the prompt for the cert, which only occurs on the first call to each new linux machine. I use this code today in one of our applications.
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "pscp";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = false;
psi.Arguments = $"-r -p -pw {passWord} \"{localFileNamePath}\" {userName}#{hostName}:{remotePath}";
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
using (Process process = new Process())
{
process.StartInfo = psi;
process.Start();
process.StandardInput.WriteLine("Y");
process.WaitForExit();
}

Use of Sox.exe in c# project

I made myself a proof of concept to test this tool to manage audio files.My purpose is to change sample rate. My first example works fine!
public class Test
{
public void SoxMethod()
{
var startInfo = new ProcessStartInfo();
startInfo.FileName = "C:\\Program Files (x86)\\sox-14-4-2\\sox.exe";
startInfo.Arguments = "\"C:\\Program Files (x86)\\sox-14-4-2\\input.wav\" -r 16000 output.wav";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = false;
startInfo.WorkingDirectory= "C:\\Program Files (x86)\\sox-14-4-2";
using (Process soxProc = Process.Start(startInfo))
{
soxProc.WaitForExit();
}
}
}
But when I want to add this tool in my bin folder but I get the exception: The directory name is invalid
public void SoxMethod()
{
var startInfo = new ProcessStartInfo();
startInfo.FileName = "bin/sox-14-4-2/sox.exe";
startInfo.Arguments = "bin/sox-14-4-2/input.wav -r 16000 output.wav";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = false;
startInfo.WorkingDirectory= "bin/sox-14-4-2";
using (Process soxProc = Process.Start(startInfo))
{
soxProc.WaitForExit();
}
}
Maybe its very obvious but I dont know what I'm doing wrong
Your working directory is wrongly set. Use AppDomain.CurrentDomain.BaseDirectory instead. That will make the Process to start at bin folder. Then, replace your file and your arguments to work relative to the working directory (thus remove the bin part of your path).
public void SoxMethod()
{
var startInfo = new ProcessStartInfo();
startInfo.FileName = "sox-14-4-2/sox.exe";
startInfo.Arguments = "sox-14-4-2/input.wav -r 16000 output.wav";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = false;
startInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
using (Process soxProc = Process.Start(startInfo))
{
soxProc.WaitForExit();
}
}

C# process RedirectStandardOutput not redirecting

I want to redirect standardoutput of a Process in a richTextBox. Here is my process configuration,
string command = "/K perl C:\\Server.pl ";
ProcessStartInfo startInfo = new ProcessStartInfo();
Process proc = new Process();
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = command;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
proc.StartInfo = startInfo;
proc.OutputDataReceived += (s, ea) => this.richTextBox1.AppendText(ea.Data);
proc.Start();
proc.BeginOutputReadLine();
Here is my Server.pl file
print "Server1 \n";
while(1)
{
print "Server \n";
sleep 1;
}
But when I run the program the cmd.exe is just black and nothing printed in richTextBox. but when I change the
startInfo.RedirectStandardOutput = false;
I have this out put in my cmd.exe:
Server1
Server
Server
Server
...
How I can work around this issue ?
Might be as simple as disabling output buffering in your perl script. This is done using the $| special variable (see perlvar).
$| = 1;
print "Server1 \n";
...

Categories

Resources