Get and Set the position in Process.StandardOutput - c#

See as an example I open CMD and navigate to the folder I want to get the data from then I use it to open the app with arugents with standard input(all synchronously) the code so far
public static Process Start(bool DoNotShowWindow = false)
{
ProcessStartInfo cmdStartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = DoNotShowWindow
};
Process cmdProcess = new Process
{
StartInfo = cmdStartInfo,
EnableRaisingEvents = true
};
return cmdProcess;
}
//in other method
Process cli = InteractWithConsoleApp.Start();
cli.Start();
cli.StandardInput.WriteLine("cd /");
cli.StandardInput.WriteLine("cd " + path);
cli.StandardInput.WriteLine("fantasygold-cli getbalance abc");
Thread.Sleep(5000);
Problem
Now when I use StandardOutput.Readline, it starts from the beginning and returns me everything like first two lines of copyright,empty lines and even the input which in my case, after waiting 5 secs for the result I want to read line or to the end depending the input from where I had inputted.
possible solution
One solution I found was to change the position but it turned out it doesn't support it and even copying to another stream reader doesn't works(the position is not by line).
Well I can use filters like check a double or for an address starts with F and has a length of 36. The problem comes when I want to get the whole JSON say for like the past transactions, for which I think using filters like '{' and then check for '}'Caveat in this would be bad code, which I don't want.
TLDR
So, what could be the solution to my problem here :)

I found the answer, to open the file in subdirectory just use this cli.StartInfo.FileName = Directory.GetCurrentDirectory() + #"\SubfolderName\fantasygold-cli";
and the arguements like getbalance as cli.StartInfo.Arguments = "getbalance amunim"

Related

git.exe writes ErrorOutput even though no error occured [duplicate]

This question already has answers here:
PowerShell displays some git command results as error in console even though operation was successful
(2 answers)
Closed 2 years ago.
I've done a git pull origin develop with help of System.Diagnosticsc.Process like this:
var gitProcess = new Process
{
StartInfo = new ProcessStartInfo
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
FileName = "git.exe",
Arguments = "pull origin develop",
WorkingDirectory = #"C:\Workspaces\MyRepo",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
}
};
gitProcess.Start();
string outputString = null;
string errorString = null;
gitProcess.OutputDataReceived += (sender, args) => outputString = string.IsNullOrWhiteSpace(outputString) ? args.Data : $"{outputString}\r\n{args.Data}";
gitProcess.ErrorDataReceived += (sender, args) => errorString = string.IsNullOrWhiteSpace(errorString) ? args.Data : $"{errorString}\r\n{args.Data}";
gitProcess.BeginErrorReadLine();
gitProcess.BeginOutputReadLine();
gitProcess.WaitForExit();
The Result is:
gitProcess.ExitCode = 0
outputString = Already up to date.
errorString = From https://mycompany.visualstudio.com/MyProject/_git/MyRepo
* branch develop -> FETCH_HEAD
Now every thing seems okay, but why did the the git.exe put the data into the errorString? It seems like normal information. This makes errorhandling hard. The ExitCode is fine it suggests success.
Any ideas why there is errordata, this happens for several other git - commands in a similar manner.
EXPECTED ANSWER
I don't want to hear about alternatives to do a git-pull in c# that's not my interest. I want to understand the behaviour of the git.exe respectivly the behaviour of System.Diagnostics.Process, basically I want to understand how and why that errordata is produced. Who is responsible for that? Is it the git.exe or the way how System.Diagnostics.Process is doing stuff.
Thank you.
Thank you for your comments, that helped. I especially researched for the main idea of stdout and stderr. The idea of stderr seems not to be only print error messages when the command failes but also to print any diagnostic information that may help understand the process but you may not want that to have in standard output.
This article explains it very well:
https://www.jstorimer.com/blogs/workingwithcode/7766119-when-to-use-stderr-instead-of-stdout
Thank you guys!

Python script execution returns null to textblock in wpf

I've looked through lots of questions about this, but I still can't figure out what's going on in my code. I have a simple form, with a browse button so you can pick a script to run. You then press run, and the output of the script populates into a textblock.
Right now, I'm running a python script that is simply:print "Hello World".
Here's my code to pick up the output:
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "python.exe",
Arguments = script,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
ErrorDialog = true,
CreateNoWindow = true //no black window
}
};
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
test.Text = output; //This is the textblock
What happens is that the textbox content changes to blank. No output is showing, just blank. This is pretty straightforward and super frustrating that I can't figure this out. Why is it returning null?
You are starting a new Process to get the output, but there can be a delay in the process to fetch output. Thus the string output is null and is stored in the TextBox. Make sure that output is printed only when the process is completed.

How to redirect STDIN .NET Process before Starting the process

Im trying to make C# application that uses hunpos tagger.
Runing hunpos-tag.exe requires three input arguments: model, inputFile, outputFile
In cmd it would look something like this:
hunpos-tag.exe model <inputFile >outputFile
If I just run it with model it writes something and waits for end command. When i tried using standard redirect I either get an exception (i solved this the code was off by a braceket i just get the or scenario now) or I get the results of running the tagger with just model argument. Here's the code:
string inputFilePath = path + "\\CopyFolder\\rr";
string pathToExe = path + "\\CopyFolder\\hunpos-tag.exe";
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = pathToExe,
UseShellExecute = false,
RedirectStandardInput = true,
WorkingDirectory = Directory.GetDirectoryRoot(pathToExe),
Arguments = path + "\\CopyFolder\\model.hunpos.mte5.defnpout",
};
try
{
Process _proc = new Process();
_proc.StartInfo.FileName = pathToExe;
_proc.StartInfo.UseShellExecute = false;
_proc.StartInfo.RedirectStandardInput = true;
_proc.StartInfo.Arguments = path + "\\CopyFolder\\model.hunpos.mte5.defnpout";
//Magic goes here
_proc.Start();
_proc.WaitForExit();
}
catch (Exception e)
{
Console.WriteLine(e);
}
Any ideas how can I redirect input before starting my process?
It is not only required to set RedirectStandardInput to true but also you need to use the input stream to write the text you want:
_proc.StandardInput.WriteLine("The text you want to write");
There's no need for that ProcessStartInfo if you're setting the info later on. Just get rid of that. And it seems you are already doing what you want. Just creating the process object doesn't start the process, Process.Start does. Just make a new StreamWriter and pass it Process.StandardInput (I think that's right, it may be something else)

Command Line Process

So after scouring the web I found a few articles (some on stackoverflow) which described how to execute a command line prompt by starting a new process in c#. The second argument, which I've commented out, works just fine, but the one I actually need (the first one) doesn't. It returns the error "Could not find or load main class edu.stanford.nlp.parser.lexparser.LexicalizedParser" When I open up a command line (non-programatically) and then execute the same command (aside from the escaped quotations) it works great. Any idea's about what the problem could be? Thanks!
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "CMD.exe",
Arguments = "/c java -mx100m -cp \"*\" edu.stanford.nlp.parser.lexparser.LexicalizedParser edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz libtest.txt",
// Arguments = "/c echo Foo",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
proc.Start();
Console.WriteLine(proc.StandardOutput.ReadToEnd());
Console.WriteLine(proc.StandardError.ReadToEnd());
Ensure that the executing path where you start your process is correct!
You can use Process Monitor from SysInternals to figure out where that class is looked for.

Exec imagemagick convert via C#

When I open a command window in windows and use the imagemagick convert command:
convert /somedir/Garden.jpg /somedir/Garden.png
It works as expected.
What I am trying to do is executing the same command as above using C#.
I tried using System.Diagnostics.Process, however, no foo.png gets created.
I am using this code:
var proc = new Process
{
StartInfo =
{
Arguments = string.Format("{0}Garden.jpg {1}Garden.png",
TEST_FILE_DIR,
TEST_FILE_DIR),
FileName = #"C:\xampp\ImageMagick-6.5.4-Q16\convert",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = false,
RedirectStandardError = false
}
};
proc.Start();
No exception gets thrown, but no .png is written, either.
My guess is that TEST_FILE_DIR contains a space - so you have to quote it.
Try this:
Arguments = string.Format("\"{0}Garden.jpg\" \"{1}Garden.png\"",
TEST_FILE_DIR,
TEST_FILE_DIR)
You might also want to give the filename including the extension, e.g.
FileName = #"C:\xampp\ImageMagick-6.5.4-Q16\convert.exe"

Categories

Resources