I'm trying to include opening Git Bash, pushing and pulling in my c# code. Whilst opening Git Bash with Process.Start() is not the problem, I cannot manage to write commands into Git Bash.
I've tried including commands in ProcessStartInfo.Arguments, as well as redirecting the standard Output. Both has not worked at all. Down below you can see the different code snippets I tried.
private void Output()
{
//Try 1
processStartInfo psi = new ProcessStartInfo();
psi.FileName = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Git\Git Bash.lnk";
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.Argument = "git add *";
Process p = Process.Start(psi);
string strOutput = p.StandardOutput.ReadToEnd();
Console.WriteLine(strOutput);
//Try 2
ProcessStartInfo psi = new ProcessStartInfo(#"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Git\Git Bash.lnk");
Process.Start(psi);
psi.Arguments = "git add *";
Process.Start(psi);
//Try 3
var escapedArgs = cmd.Replace("\"", "\\\"");
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = #"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Git\Git Bash.lnk",
Arguments = "cd C:\\Users\\strit\\autocommittest2\\autocommittest2\n",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
string result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
}
Git Bash opens but nothing is written in the command line.
I know it is old question, still adding answer as few days ago I was also facing same issue.
I think what you are missing is -c parameter. I used below code and it solved this issue. -c tells git-bash to execute whatever follows, it is similar to -cmd parameter in command line.
In below mentioned function -
fileName = path of git-bash.exe.
command = git command which you want to execute.
workingDir = Local path of git repository.
public static void ExecuteGitBashCommand(string fileName, string command, string workingDir)
{
ProcessStartInfo processStartInfo = new ProcessStartInfo(fileName, "-c \" " + command + " \"")
{
WorkingDirectory = workingDir,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true
};
var process = Process.Start(processStartInfo);
process.WaitForExit();
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
var exitCode = process.ExitCode;
process.Close();
}
I hope it solves the issue.
I think you are on the right way. I would try to use the git in the path, but it should be possible to also use the git-bash.exe directly, at my machine it is located here: C:\Program Files\Git\git-bash.exe.
Process gitProcess = new Process();
gitInfo.Arguments = YOUR_GIT_COMMAND; // such as "fetch origin"
gitInfo.WorkingDirectory = YOUR_GIT_REPOSITORY_PATH;
gitInfo.UseShellExecute = false;
gitProcess.StartInfo = gitInfo;
gitProcess.Start();
string stderr_str = gitProcess.StandardError.ReadToEnd(); // pick up STDERR
string stdout_str = gitProcess.StandardOutput.ReadToEnd(); // pick up STDOUT
gitProcess.WaitForExit();
gitProcess.Close();
Like #S.Spieker already told you in it's good answer, no need to use git bash (it makes it harder to achieve and less performant), just call directly the git executable.
You could have a look to the GitExtensions code that is doing that: https://github.com/gitextensions/gitextensions/blob/027eabec3be497f8d780cc68ece268c64a43a7d5/GitExtensionsVSIX/Git/GitCommands.cs#L112
You could also achieve what you want using libgit2sharp (https://github.com/libgit2/libgit2sharp). That could be easier if you want to interpret the results of the command run.
Related
I am using the below code C# Process instance to do a CSV import for PostgreSQL.
Process process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = #"cmd.exe",
Arguments = $"/c cat \"{filePath}\" | psql -h 127.0.0.1 -U {user} -d {dbname} -w -c \"copy data_temp from stdin csv header\" ",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
string result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
process.Dispose();
It works but I look in task manager and after a while there is lot of PostgreSQL processes running and eventually the database gets locked.
Am I not closing the process down properly? How can I ensure it doesn't stay open?
Not to sure if this could help or not but here are two examples I have of killing processes via msiexec and Exe.
Uninstalling Msiexec.exe files…
Process x = new Process();
x.StartInfo.FileName = "msiexec.exe";
x.StartInfo.Arguments = "/qb /x {81681F4C-83F1-4F22-9AEB-C7DA7C372EA2}";[quiet uninstall]
x.Start();
x.WaitForExit();
and
Uninstalling exe (file path method, not msiexec)
Process a = new Process();
a.StartInfo.FileName = JPRO_8_5_0; //defined in a string before hand.
a.StartInfo.Arguments = "/uninstall /quiet";
a.Start();
a.WaitForExit();
You can try making the filename a string that is defined before instead of having it as #"cmd.exe", that might help!
I'm trying to write a C# console application that will launch runas.exe through cmd then run another application as that user. I've taken one of the suggestions listed below (and added a little bit) as it seems the most promising.
Process cmd = new Process();
ProcessStartInfo startinfo = new ProcessStartInfo("cmd.exe", #"/K C:\Windows\System32\runas.exe /noprofile /user:DOMAIN\USER'c:\windows\system32\notepad.exe\'")
{
RedirectStandardInput = true,
UseShellExecute = false
};
cmd.StartInfo = startinfo;
cmd.Start();
StreamWriter stdInputWriter = cmd.StandardInput;
stdInputWriter.Write("PASSWORD");
cmd.WaitForExit();
When I launch the application it asks for the password before the command itself causing there to be an error with runas.exe
I'm pretty sure UseShellExecute = false is causing the error but the StreamWriter doesn't work without it so I'm not sure what to do.
The /c argument runs comman line and terminates, so you could not see results (and it's a large C), see her : http://ss64.com/nt/cmd.html
Try to use "/K".
I did it with your command and i see results in another window.
ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/K ping PC -t");
Process.Start(startInfo);
Your process should have RedirectStandardInput = true
var p = new Process();
var startinfo = new ProcessStartInfo("cmd.exe", #"/C C:\temp\input.bat")
{
RedirectStandardInput = true,
UseShellExecute = false
};
p.StartInfo = startinfo;
p.Start();
StreamWriter stdInputWriter = p.StandardInput;
stdInputWriter.Write("y");
This program launches input.bat, and then sends the value y to it's standard input.
For completeness, input.bat example:
set /p input=text?:
echo %input%
I found a solution in the following post. I had to forgo most of the structure I was working with but I can now successfully run notepad as my desired user with the code listed below.
var pass = new SecureString();
pass.AppendChar('p');
pass.AppendChar('a');
pass.AppendChar('s');
pass.AppendChar('s');
pass.AppendChar('w');
pass.AppendChar('o');
pass.AppendChar('r');
pass.AppendChar('d');
var runFileAsUser = new ProcessStartInfo
{
FileName = "notepad",
UserName = "username",
Domain = "domain",
Password = pass,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
Process.Start(runFileAsUser);
I'm writing a c# application for validating the detailed information about no.of lines changes in SVN commit. After providing the below arguments in command prompt, it displays the revision number, author name and last changed date etc...
Argument:
svn info –r {revision no} {Source path}
Eg - svn info -r 113653 "F:\SVN"
I have to achieve the same in C# also. While giving the above arguments in C#, it should read the output(revision number, author name and last changed date) from the command prompt and store it in a string. I have tried the StandardOutput.ReadToEnd() but couldn't meet my requirement. Any detailed explanation will be helpful.
Have you tried just running the command from a command prompt with C# as explained in this question?
string strCmdText = #"/C svn info -r 113653 ""F:\SVN""";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);
You can use the following method to run a command and retrieve the standard output from the console :
public static string StdOut(string args)
{
string cmdOut = "";
ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/C " + args)
{
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
cmdOut = ExecuteCommand(cmdOut, startInfo);
return cmdOut;
}
It will return the output as a string.
You will also need this method (as it is used in the above):
private static string ExecuteCommand(string cmdOut, ProcessStartInfo startInfo)
{
Process p = Process.Start(startInfo);
p.OutputDataReceived += (x, y) => cmdOut += y.Data;
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
return cmdOut;
}
p.OutputdataReceived is a DataReceivedEventHandler and it will concatenate any std output received onto the cmdOut variable.
I have a program in Debian which needs root privileges and myuser has to run it, but I have to do the call from a .NET application (C#) running in mono.
In /etc/sudoers, I have add the line:
myuser ALL = NOPASSWD: /myprogram
so sudo ./myprogram works for myuser.
In. NET I use in my code
string fileName = "/myprogram";
ProcessStartInfo info = new ProcessStartInfo (fileName);
...
How can I do the call "sudo fileName"? It doesn't work by the time...
thank you, Monique.
The following worked for me in a similar situation, and demonstrates passing in multiple arguments:
var psi = new ProcessStartInfo
{
FileName = "/bin/bash",
UseShellExecute = false,
RedirectStandardOutput = true,
Arguments = string.Format("-c \"sudo {0} {1} {2}\"", "/path/to/script", "arg1", arg2)
};
using (var p = Process.Start(psi))
{
if (p != null)
{
var strOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
}
You just need to pass your program as the argument to the sudo command like this:
ProcessStartInfo info = new ProcessStartInfo("sudo", "/myprogram");
Process.Start(info);
I need to start the command window with some arguments and run more commands inside.
For example, launch a test.cmd and run mkdir.
I can launch the test.cmd with processstartinfo , but i am not sure how to run further commands. Can I pass further arguments to the test.cmd process?
How do I go about this?
Unable to add comments to answer... SO writing here.
Andrea, This is what I was looking for. However the above code doesnt work for me.
I am launching a test.cmd which is new command environment (like razzle build environment) and I need to run further commands.
psi.FileName = #"c:\test.cmd";
psi.Arguments = #"arg0 arg1 arg2";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
Process p = new Process();
p.StartInfo = psi;
p.Start();
p.StandardInput.WriteLine(#"dir>c:\results.txt");
p.StandardInput.WriteLine(#"dir>c:\results2.txt");
You can send further commands to cmd.exe using the process
standard input. You have to redirect it, in this way:
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
var process = new Process {StartInfo = startInfo};
process.Start();
process.StandardInput.WriteLine(#"dir>c:\results.txt");
process.StandardInput.WriteLine(#"dir>c:\results2.txt");
process.StandardInput.WriteLine("exit");
process.WaitForExit();
Remember to write "exit" as your last command, otherwise the cmd process doesn't terminate correctly...
The /c parameter to cmd.
ProcessStartInfo start = new ProcessStartInfo("cmd.exe", "/c pause");
Process.Start(start);
(pause is just an example of what you can run)
But for creating a directory you can do that and most other file operations from c# directly
System.IO.Directory.CreateDirectory(#"c:\foo\bar");
Start a cmd from c# is useful only if you have some big bat-file that you don't want to replicate in c#.
What are you trying to achieve? Do you actually need to open a command window, or do you need to simply make a directory, for example?
mkdir is a windows executable - you can start this program in the same way you start cmd - there's no need to start a command window process first.
You could also create a batch file containing all the commands you want to run, then simply start it using the Process and ProcessStartInfo classes you're already using.
How come this doesn't work?
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = false
};
var process = new Process { StartInfo = startInfo };
process.Start();
process.StandardInput.WriteLine(#" dir");
process.WaitForExit();