running bat file through c#.net code reg - c#

I have run the bat file through dotnet in c# is as below
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "d://s.bat";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
it works fine while running through dotnet ide.
But my problem is when ever i run the above code after publishing through IIS it returns me error as
StandardOut-has-not-been-redirected-or-the-process-hasn-t-started-yet.
can you give me some guide lines to solve this problem?

Do this way, to overcome the error:-
StringBuilder content = new StringBuilder();
while ( ! p.HasExited ) {
content.Append(p.StandardOutput.ReadToEnd());
}
string output = content.ToString();

You have to use the RedirectStandardOutput = true.
Link from MSDN
Quote from link:
ProcessStartInfo.RedirectStandardOutput Property
Gets or sets a value that indicates whether the output of an application is written to the Process.StandardOutput stream.
A snippet from my issue to the same problem, when i was making sure our server was starting.
if (IsProcessRunning(ServerProcessName)) { return; }
var p = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = path,
RedirectStandardOutput = true,
UseShellExecute = false
}
};
p.Start();
var a = "";
while (!a.Contains("ServicesStarted"))
{
a = p.StandardOutput.ReadLine();
}

Related

How to take window ID of a created process in c#?

I am working on a C# .net core project.I created a process to run "xdotool windowactivate $windowpid".I should store the windowID which process run on it.The solution could be any property of xdotool which i couldn't find,or Is there any way to take windowId of a process when it is created?
Another Try is that:
I created my pages with this method. I tried to take mainwindowtitle of process;because of single process,i couldn't take the titles.
static List<string> chromeTitles = new List<string>();
public static Process StartChrome(string filePath)
{
string dataDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Chrome-UserData");
filePath += " --user-data-dir=" + dataDirectory;
var Chrome = new Process
{
StartInfo =
{
FileName = "C:/Program/chrome.exe",
Arguments = filePath,
UseShellExecute = false,
CreateNoWindow=true,
WindowStyle = ProcessWindowStyle.Maximized,
}
};
Chrome.Start();
string title = Chrome.MainWindowTitle;
chromeTitles.Add(title);
}
Then I call it :
StartChrome("https://tr.wikipedia.org/wiki/Anasayfa");
Thread.Sleep(2000);
StartChrome("https://tureng.com/");
You can use the Process class for accessing more capabilities.
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "xdotool.exe";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.Arguments = $"windowactivate $windowpid";
process.StartInfo = startInfo;
process.Start();
To get the PID of the process that got run by the code, you can use Process.ID property:
process.Id;
if you want to read the output, you can add this code:
string output = process.StandardOutput.ReadToEnd();
To get Output, startInfo.RedirectStandardOutput should be True.

How to execute a terminal command in Xamarin.Mac and read-in its output

We are writing a Xamarin.Mac application. We need to execute a command like "uptime" and read it's output into an application to parse.
Could this be done? In Swift and Objective-C there is NTask, but I don't seem to be able to find any examples in C#.
Under Mono/Xamarin.Mac, you can the "standard" .Net/C# Process Class as the Process gets mapped to the underlaying OS (OS-X For Mono, MonoMac and Xamarin.Mac, and Mono for *nix).
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();
// To avoid deadlocks, always read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Xamarin: https://developer.xamarin.com/api/type/System.Diagnostics.Process/
MSDN: https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
Example from my OS-X C# code, but it is cross-platform as it works as is under Windows/OS-X/Linux, just the executable that you are running changes across the platforms.
var startInfo = new ProcessStartInfo () {
FileName = Path.Combine (commandPath, command),
Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
UserName = System.Environment.UserName
};
using (Process process = Process.Start (startInfo)) { // Monitor for exit}
process.WaitForExit ();
using (var output = process.StandardOutput) {
Console.Write ("Results: {0}", output.ReadLine ());
}
}
Here is an example taken from Xamarin forum:
var pipeOut = new NSPipe ();
var t = new NSTask();
t.LaunchPath = launchPath;
t.Arguments = launchArgs;
t.StandardOutput = pipeOut;
t.Launch ();
t.WaitUntilExit ();
t.Release ();
var result = pipeOut.ReadHandle.ReadDataToEndOfFile ().ToString ();

How do I execute a shell script in C#?

I have one file which contains a Unix shell script. So now I wanted to
run the same in .NET. But I am unable to execute the same.
So my point is, is it possible to run the Unix program in .NET? Is there any API like NSTask in Objective-C for running Unix shell scripts so any similar API in .NET?
It has been answered before. Just check this out.
By the way, you can use:
Process proc = new Process {
StartInfo = new ProcessStartInfo {
FileName = "program.exe",
Arguments = "command line arguments to your executable",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
After that start the process and read from it:
proc.Start();
while (!proc.StandardOutput.EndOfStream) {
string line = proc.StandardOutput.ReadLine();
// Do something with line
}
ProcessStartInfo frCreationInf = new ProcessStartInfo();
frCreationInf.FileName = #"C:\Program Files\Git\git-bash.exe";
frCreationInf.Arguments = "Test.sh";
frCreationInf.UseShellExecute = false;
var process = new Process();
process.StartInfo = frCreationInf;
process.Start();
process.WaitForExit();

Running batch file containing NuGet commands from C#

I have a batch file containing the following commands:
cd C:\myfolder
NuGet Update -self
NuGet pack mypackage.nuspec
myfolder contains mypackage.nuspec and NuGet.exe. I try to run this command with C# using the following function:
private static int ExecuteCommand(string path)
{
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo(path);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = false;
ProcessInfo.WorkingDirectory = new System.IO.FileInfo(path).DirectoryName;
ProcessInfo.EnvironmentVariables["EnableNuGetPackageRestore"] = "true";
// *** Redirect the output ***
ProcessInfo.RedirectStandardError = true;
ProcessInfo.RedirectStandardOutput = true;
Process = Process.Start(ProcessInfo);
Process.WaitForExit();
// *** Read the streams ***
string output = Process.StandardOutput.ReadToEnd();
string error = Process.StandardError.ReadToEnd();
int ExitCode = Process.ExitCode;
Process.Close();
return ExitCode;
}
However, my commands are not executed. What is causing this behavior and what is the solution? Those strings will probably be used in the future, I'll update my question then (just to prevent chriticism :)).
This is the final version of the function:
private static ShellCommandReturn ExecuteCommand(string path)
{
ProcessStartInfo processInfo;
Process process;
processInfo = new ProcessStartInfo(path);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.WorkingDirectory = new System.IO.FileInfo(path).DirectoryName;
processInfo.EnvironmentVariables["EnableNuGetPackageRestore"] = "true";
// *** Redirect the output ***
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
process = Process.Start(processInfo);
process.WaitForExit();
// *** Read the streams ***
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
int exitCode = process.ExitCode;
process.Close();
return new ShellCommandReturn { Error = error, ExitCode = exitCode, Output = output };
}
ShellCommandReturn is a simple custom class with a few data members where error, output and exit code of a shell command are stored.
Thanks.
EDIT: After a certain amount of collaboration :)
The problem is that this is executing in the context of a web application, which doesn't have the same environment variables set.
Apparently setting:
startInfo.EnvironmentVariables["EnableNuGetPackageRestore"] = "true"
(using the naming of my final code below) fixes the problem.
Old answer (still worth reading)
Look at this code:
ProcessInfo = new ProcessStartInfo(path);
ProcessInfo.CreateNoWindow = false;
ProcessInfo.UseShellExecute = true;
ProcessInfo.WorkingDirectory = new System.IO.FileInfo(path).DirectoryName;
Process = Process.Start(path);
You're creating a ProcessStartInfo, but then completely ignoring it. You should be passing it into Process.Start. You should also rename your variables. Conventionally local variables start with lower case in C#. Additionally, it's a good idea to initialize variables at the point of first use, where possible. Oh, and import namespaces so you don't fully qualified names such as System.IO.FileInfo in your code. Finally, object initializers are useful for classes like ProcessStartInfo:
var startInfo = new ProcessStartInfo(path) {
CreateNoWindow = false,
UseShellExecute = true,
WorkingDirectory = new FileInfo(path).DirectoryName;
};
var process = Process.Start(startInfo);

"StandardIn has not been redirected" error in .NET (C#)

I want to do a simple app using stdin. I want to create a list in one program and print it in another. I came up with the below.
I have no idea if app2 works however in app1 I get the exception "StandardIn has not been redirected." on writeline (inside the foreach statement). How do I do what I intend?
NOTE: I tried setting UseShellExecute to both true and false. Both cause this exception.
//app1
{
var p = new Process();
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.FileName = #"path\bin\Debug\print_out_test.exe";
foreach(var v in lsStatic){
p.StandardInput.WriteLine(v);
}
p.StandardInput.Close();
}
//app 2
static void Main(string[] args)
{
var r = new StreamReader(Console.OpenStandardInput());
var sz = r.ReadToEnd();
Console.WriteLine(sz);
}
You never Start() the new process.
You must ensure ShellExecute is set to false in order for the redirection to work correctly.
You should also open a streamwriter on it, start the process, wait for the process to exit, and close the process.
Try replacing these lines:
foreach(var v in lsStatic){
p.StandardInput.WriteLine(v);
}
p.StandardInput.Close();
with these:
p.Start();
using (StreamWriter sr= p.StandardInput)
{
foreach(var v in lsStatic){
sr.WriteLine(v);
}
sr.Close();
}
// Wait for the write to be completed
p.WaitForExit();
p.Close();
if you would like to see a simple example of how to write your process to a Stream use this code below as a Template feel free to change it to fit your needs..
class MyTestProcess
{
static void Main()
{
Process p = new Process();
p.StartInfo.UseShellExecute = false ;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = #"path\bin\Debug\print_out_test.exe";
p.StartInfo.CreateNoWindow = true;
p.Start();
System.IO.StreamWriter wr = p.StandardInput;
System.IO.StreamReader rr = p.StandardOutput;
wr.Write("BlaBlaBla" + "\n");
Console.WriteLine(rr.ReadToEnd());
wr.Flush();
}
}
//Change to add your work with your for loop
From http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardinput.aspx
You must set UseShellExecute to false if you want to set RedirectStandardInput to true. Otherwise, writing to the StandardInput stream throws an exception.
One might expect it to be false by default, that doesn't seem to be the case.

Categories

Resources