Vbs script working fine with CMD but not in Code - c#

When I execute the script via code it's going in an infinite loop. But same script working in CMD
tried with CMD and It's working but not working in code. Take any VB Script as a sample and validate.
private string excecuteScript(string retValue)
{
try
{
string filetoexecute = Path.Combine(Application.StartupPath, Path.GetExtension(ScriptName).EndsWith(".vbs",StringComparison.InvariantCultureIgnoreCase) ? "AA_MyVB.vbs" : "AA_MyJS.js");
filetoexecute = string.Format("\"" + filetoexecute + "\"");
string arguments = " " + filetoexecute + " " + ScriptInputPara + " \"" + ScriptName + "\" ";
ProcessStartInfo startInfo = new ProcessStartInfo()
{
FileName = Path.Combine(Environment.SystemDirectory, "WScript.exe"),
Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
var myProcess = CommonMethods.InvokeProcess(startInfo);
StreamReader errorStream = myProcess.StandardError;
StreamReader outputStream = myProcess.StandardOutput;
string theOutput = string.Empty;
bool stopWhile = false;
while (!stopWhile)
{
stopWhile = myProcess.HasExited;
if (CmdTask.IsTaskTimedout)
{
stopWhile = true;
myProcess.Kill();
}
}
theOutput += outputStream.ReadLine();
TheError += errorStream.ReadToEnd();
if (myProcess.ExitCode != 0)
{
TheError = "Error occurred while executing script file";
}
if (IsScriptTask && !string.IsNullOrEmpty(theOutput) && !string.IsNullOrEmpty(ScriptOutputPara))
CmdTask.SetVariableValue(ScriptOutputPara, theOutput);
}
catch (Exception ex)
{
retValue = (ex.Message);
}
return retValue;
}
Actual: myProcess.HasExited returns false
Expected: myProcess.HasExited returns true
if I execute theOutput += outputStream.ReadLine(); before while loop then myProcess.HasExited returns true...

Related

I get a can't execute binary file error when running a bash command from C#

I've created a Discord Bot with which you can interact (running on a Raspberry Pi with a default Raspberry Pi OS). I also added a command to execute a shell command. My code:
ProcessStartInfo inf = new()
{
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
FileName = "/bin/bash",
Arguments = command,
};
if (Process.Start(inf) is Process cmd)
{
string ret = "Output: " + await cmd.StandardOutput.ReadToEndAsync();
ret += "\nError Output: " + await cmd.StandardError.ReadToEndAsync();
await Program.Log(ret);
return ret;
}
When I set command to "echo Hello, World!" I just get the error
/usr/bin/echo: /usr/bin/echo: cannot execute binary file
from the StandardOutput.
What am I doing wrong?
You have to pass -c parameter to bash if you want execute something through it
ProcessStartInfo inf = new()
{
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
FileName = "/bin/bash",
Arguments = $"-c \"{command}\""
};
if (Process.Start(inf) is Process cmd)
{
string ret = "Output: " + await cmd.StandardOutput.ReadToEndAsync();
ret += "\nError Output: " + await cmd.StandardError.ReadToEndAsync();
await Program.Log(ret);
return ret;
}

StandardOutput.ReadToEnd() always NULL

I have a problem with this function. It is supposed to output an install command to a textbox but install.StandardOutput.ReadToEnd() is always null.
I get the error: Expression cannot be evaluated because there is a native frame at the top of the call stack
Can you help me out with this?
Process install = new Process();
install.StartInfo.FileName = "cmd.exe";
install.StartInfo.UseShellExecute = false;
install.StartInfo.Arguments = "/all";
install.StartInfo.CreateNoWindow = true;
install.StartInfo.RedirectStandardInput = true;
install.StartInfo.RedirectStandardOutput = true;
install.Start();
if (CB_MultiADB.Checked == true)
{
install.StandardInput.WriteLine("FOR /F \"skip=1\" %%x IN ('adb devices') DO start cmd.exe #cmd /k" + InstallOption + InstallPfad + "\"");
}
else
{
install.StandardInput.WriteLine("adb install" + InstallOption + InstallPfad + "\"");
InstallAusgabe = install.StandardOutput.ReadToEnd();
string Index = "adb install";
int Indexnr = InstallAusgabe.IndexOf(Index);
string SubInstall = InstallAusgabe.Substring(Indexnr, 100);
TB_Ausgabe.Text = SubInstall;
}

how to execute a .rmd file from c# and get the execution response - Dot Net

I am having a .rmd file [ R mark down file], it will do data validation for some specific scenario, i wanted to execute the rmd file from console application using c#, can some one help me doing the execution.
Finally I have done the above requirement as below,posting here since it can help some one on implementation
- created a R script and invoked Rmd script from the R script
- used command line code for invoking R script from C#.
R Script Sample:
rmarkdown::render(
input = rmdfilepath,
output_file = outputfilepath,
output_format = "all", output_options = list())
c# Sample:
private static string RunRScript(string rpath, string scriptpath, string inputfilepath,
string outputfilepath)
{
try
{
var info = new ProcessStartInfo
{
FileName = rpath,
WorkingDirectory = Path.GetDirectoryName(rpath),
Arguments = scriptpath + " " + inputfilepath + " " + outputfilepath,
RedirectStandardOutput = true,
CreateNoWindow = true,
UseShellExecute = false
};
using (var proc = new Process { StartInfo = info })
{
proc.Start();
return proc.StandardOutput.ReadToEnd();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return string.Empty;
}

Programmatically calling cmd.exe from MVC4

I’m facing some issue w.r.t calling a .exe from MVC4.
I have a ActionResult method where I want to start a command prompt locally but it shouldnot run as IISPool Identity instead it should run as a user logged in, unlike we do RunAs manually.
I have to pass parameter to the command line and in turn receive the output. I have written a code but it is not returning anything. Can someone highlight where I made some mistake.
string _commandParameter = #"whoami";
try
{
var process = new Process
{
StartInfo =
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
Verb = "runas",
FileName = #"C:\Windows\System32\cmd.exe",
Domain = "dir",
UserName = userID,
Password = GetSecureString(userpassword),
Arguments = _commandParameter
}
};
process.Start();
string readToEndOutput = process.StandardOutput.ReadToEnd();
string readToEndError = process.StandardError.ReadToEnd();
process.WaitForExit();
}
catch (Exception ex)
{
log.Info("error as StackTrace Exception in Input ActionResult -" + ex.StackTrace.ToString());
log.Info("error as Message Exception in Input ActionResult -" + ex.Message.ToString());
}
public static SecureString GetSecureString(string str)
{
SecureString result = new SecureString();
try
{
if (string.IsNullOrWhiteSpace(str))
return null;
else
{
foreach (char c in str.ToCharArray())
result.AppendChar(c);
return result;
}
}
catch (Exception ex)
{
log.Info("Cannot create password-" + ex.StackTrace.ToString());
}
return result;
}
The output

Ghost script command dosent wait for WaitForExit()

Hi guys im trying to execute gs command by creating a process and i want it to wait until the process is completed. I used waitforexit() but its surpassing waitforexit().
public async void pdf2Png(string name, string pdf, int lastPage)
{
Stopwatch stopwatch = Stopwatch.StartNew();
Response.Write((stopwatch.ElapsedMilliseconds / 1000) + " pdf 2 png" + "<br>");
Process obj_process = null;
ProcessStartInfo obj_startinfo = null;
StreamWriter obj_writer = null;
string sOutputFile = Path.Combine(Path.GetDirectoryName(pdf), name + "%d.png"); ;
string inputFilePath = pdf;
int lP = lastPage;
Response.Write(sOutputFile + " : " + inputFilePath + "<br>");
string str_command = string.Format("gswin64 -dSAFER -dBATCH -dNOPAUSE -dFirstPage=1 -dLastPage=\"{0}\" -sDEVICE=png16m -r600 -sOutputFile=\"{1}\" \"{2}\"",
lP, sOutputFile, inputFilePath);
obj_startinfo = new ProcessStartInfo("cmd.exe");
obj_startinfo.UseShellExecute = false;
obj_startinfo.RedirectStandardInput = true;
obj_startinfo.RedirectStandardError = true;
obj_startinfo.RedirectStandardOutput = true;
obj_startinfo.CreateNoWindow = true;
obj_startinfo.ErrorDialog = false;
obj_startinfo.WindowStyle = ProcessWindowStyle.Hidden;
obj_process = Process.Start(obj_startinfo);
obj_writer = obj_process.StandardInput;
obj_writer.WriteLine(str_command);
obj_writer.Flush();
obj_writer.Close();
obj_writer.Dispose();
obj_writer = null;
obj_process.WaitForExit();
System.IO.File.WriteAllText(#"D:\shits not working.txt", str_command);
stopwatch.Stop();
Response.Write((stopwatch.ElapsedMilliseconds / 1000) + " pdf 2 png" + "<br>");
}
the line below "Waitforexit()" gets executed even before the png gets created and exits the process. what can i do?

Categories