Execute dotnet command with Process in C# - c#

I have following C# lines of code where open process and run dotnet command to open my console application (created with .net standard/core)
var args = new Dictionary<string, string> {
{ "-p", "title"},
{ "-l", "games"},
...
};
var arguments = string.Join(" ", args.Select((k) => string.Format("{0} {1}", k.Key, "\"" + k.Value + "\"")));
var dllPath = #"C:\Users\xyz\Documents\Visual Studio 2017\myConsole\bin\Debug\netcoreapp2.1\myConsole.dll";
ProcessStartInfo procStartInfo = new ProcessStartInfo();
procStartInfo.FileName = "C:\....\cmd.exe";
procStartInfo.Arguments = $"dotnet \"{dllPath}\" {arguments}";
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
StringBuilder sb = new StringBuilder();
Process pr = new Process();
pr.StartInfo = procStartInfo;
pr.OutputDataReceived += (s, ev) =>
{
if (string.IsNullOrWhiteSpace(ev.Data))
{
return;
}
string[] split = ev.Data.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
int.TryParse(split[split.Length - 1], out output);
};
pr.ErrorDataReceived += (s, err) =>
{
// do stuff here
};
pr.EnableRaisingEvents = true;
pr.Start();
pr.BeginOutputReadLine();
pr.BeginErrorReadLine();
pr.WaitForExit();
The command Arguments result is:
dotnet "C:\Users\xyz\Documents\Visual Studio 2017\myConsole\bin\Debug\netcoreapp2.1\myConsole.dll" -p "title" -l "games" -s "" -r "none" -k "0" -d "/path/" -f ""
But for ev.Data from OutputDataReceived event looks like:
Microsoft Windows [Version 10.0.16299.665]
(c) 2017 Microsoft Corporation. All rights reserved.
and that's all...
I expected to run dotnet command to dll.
If I run manually the result command dotnet .... above, works fine. But not from my C# code. Why ?

Because cmd returns:
Microsoft Windows [Version 10.0.16299.665]
(c) 2017 Microsoft Corporation. All rights reserved.
You need to call
procStartInfo.FileName = "dotnet"

Related

Executing Commands in CMD and accessing a git on-premises server

I have configured password less auth for my git on-premises. Now I want to first go to the ssh dir in local machine and then access the git server from there all using cmd. I am doing this whole thing using C# code. Below is my code.
ProcessStartInfo processStartInfo = null;
Process process = null;
Process main = null;
ProcessStartInfo processMainInfo = null;
processStartInfo = new ProcessStartInfo("cmd.exe","ssh swx#192.168.12.232");
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.WorkingDirectory = #"C:\Users\xyz\.ssh";
process = new Process();
process.StartInfo = processStartInfo;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.UseShellExecute = false;
process.Start();
process.StandardInput.WriteLine("/c cd git_home && git log");
string returnValue = process.StandardOutput.ReadToEnd();
I know that /c first executes the and then terminates. I tried to use && for the whole command like this :
> ssh swx#192.168.12.232 && cd git_home && git log
but in this case only ssh swx#192.168.12.232 this part is getting executed and the other cd git_home && git log are not.
Can anyone help me here?
My main goal here is to execute two commands one after another 1st :
> ssh swx#192.168.12.232
this should get executed it will give me access to the server form the cmd and after that
> cd git_home && git log
which will get me to the git repo and give me all the logs as output in string returnValue.
or if there is some more efficient way pls suggest.
Edit
I tried to run the commands one after another below is the code:
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine(" C:");
sw.WriteLine(#"cd C:\Users\xyz\.ssh");
sw.WriteLine(" ssh swx#192.168.12.232");
sw.WriteLine("cd git_home");
sw.WriteLine("git log");
}
string aaa = p.StandardOutput.ReadToEnd();
}
But the string aaa returns :
Microsoft Windows [Version 10.0.19042.1023]
(c) Microsoft Corporation. All rights reserved.
D:\Kovair Projects\Adapters\KOVAIR_Git_KovairGitAdapter_2.20 - EventService-BAK\Source\TestAPP\bin> C:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE>cd C:\Users\xyz\.ssh
C:\Users\xyz\.ssh> ssh swx#192.168.12.232
C:\Users\xyz\.ssh>cd git_home
C:\Users\xyz\.ssh>git log
C:\Users\xyz\.ssh>
what can I do so that I can execute the last 2 commands in the linux server?
swx#192.168.12.232 "cd git_home ; git log" execute this command this might help.

c# console.clear wpf result of cmd command in variable

I have function that get me a whole cmd
public void GetMovieData(string FileName)
{
string command = "mediainfo --Inform=file://custom.txt " + FileName;
ProcessStartInfo psi = new ProcessStartInfo();
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.FileName = "cmd.exe";
psi.UseShellExecute = false;
using (Process p = Process.Start(psi))
{
p.StandardInput.Flush();
p.StandardInput.WriteLine(command);
p.StandardInput.Flush();
p.StandardInput.Close();
t_Dane_tech.Text = p.StandardOutput.ReadToEnd();
}
}
now i want only get these lines that are below command. Now when i hit the button i get info: Microsoft Windows [Version 10.0.16299.309]
(c) 2017 Microsoft Corporation bla bla bla and result of my command. I just want that command result... It can be done?
string command = "mediainfo --Inform=file://custom.txt " + FileName + " > "plik.txt";
And now streamreader and at the end of the function delete file. I think i overthink it but it is just fine :D

Open Visual Studio command prompt from C# code

I am trying to open Visual studio Command prompt using C# code.
Here is my code
private void Execute(string vsEnvVar)
{
var vsInstallPath = Environment.GetEnvironmentVariable(vsEnvVar);
// vsEnvVar can be VS100COMNTOOLS, VS120COMNTOOLS, VS140COMNTOOLS
if (Directory.Exists(vsInstallPath))
{
var filePath = vsInstallPath + "vsvars32.bat";
if (File.Exists(filePath))
{
//start vs command process
Process proc = new Process();
var command = Environment.GetEnvironmentVariable("ComSpec");
command = #"" + command + #"";
var batfile = #"E:\Test\vstest.bat";
var args = string.Format("/K \"{0}\" \"{1}\"" ,filePath, batfile);
proc.StartInfo.FileName = command;
proc.StartInfo.Arguments = args;
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.UseShellExecute = false;
proc.Start();
}
else
{
Console.WriteLine("File Does not exists " + filePath);
}
}
}
But the args string is not getting properly formatted.
I am getting below formatted string
"/K \"C:\\Program Files\\Microsoft Visual Studio 10.0\\Common7\\Tools\\vsvars32.bat\" \"E:\\Test\\vstest.bat\""
extra "\" is getting added.
Please point out what I am missing.
Thanks
The string is being formatted as you asked, but you have asked for the wrong thing. "E:\Test\VStest.bat" is being passed as an argument to VCVars.bat, but I suspect you want it to be executed after it.
Try this:
var args = string.Format("/S/K \" \"{0}\" && \"{1}\" \"" ,filePath, batFile);
This should produce:
"/S/K \" \"C:\\Program Files\\Microsoft Visual Studio 10.0\\Common7\\Tools\\vsvars32.bat\" && \"E:\\Test\\vstest.bat\" \" \"
Which as a string is:
/S/K " "C:\Program Files\Microsoft Visual Studio 10.0\Common7\Tools\vsvars32.bat" && "E:\Test\vstest.bat" "

Runing command into CMD and get output into variable using C#

I need to run a command into CMD window and want to get result into a variable.
I used below code to do the same but the out put is incorrect
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = " wmic.exe /node:(computername or ip address) computersystem get username ",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
string line = "";
while (!proc.StandardOutput.EndOfStream)
{
line += (line.Length > 0 ? "-----" : "") + proc.StandardOutput.ReadLine();
}
proc.WaitForExit();
Out put
Microsoft Windows [Version 6.1.7601]-----Copyright (c) 2009 Microsoft Corporation. All rights reserved.----------C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0>
But when i run this command into CMD window it shows the current logged in users name.
Can any one help me to solve the issue.
Note :- The given command is used to get the current logged in users
name on network system by using it's IP Address.
What you need is the /c option for cmd
C:\>cmd /?
Starts a new instance of the Windows command interpreter
CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
[[/S] [/C | /K] string]
/C Carries out the command specified by string and then terminates
I would question the need for cmd.exe here. You can just invoke wmic directly as below
var proc = new Process {
StartInfo = new ProcessStartInfo {
FileName = "wmic.exe",
Arguments = "/node:localhost computersystem get username ",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
string line = "";
while (!proc.StandardOutput.EndOfStream) {
line += (line.Length > 0 ? "-----" : "") + proc.StandardOutput.ReadLine();
}
proc.WaitForExit();
Why would you go to the trouble of invoking a commandline tool and parsing its results if System.Management has all the classes you need to obtain the information in-process and managed?
var ip = "127.0.0.1";
var scope = new ManagementScope(
String.Format("\\\\{0}\\root\\cimv2", ip),
new ConnectionOptions { Impersonation = ImpersonationLevel.Impersonate });
scope.Connect();
var users = new ManagementObjectSearcher(
scope,
new ObjectQuery("Select * from Win32_LoggedonUser"))
.Get()
.GetEnumerator();
while(users.MoveNext())
{
var user = users.Current["antecedent"];
var mo = new ManagementObject(new ManagementPath(user.ToString()));
try
{
var username = mo.Properties["name"];
Console.WriteLine("username {0}", username.Value);
}
catch
{
Console.WriteLine(mo);
}
}
All you have to do is create a ManagementScope and then use the ManagementObjectSearcher to run any WMI Query Language statement by using one of the available WMI Classes.
If you have a working wmic call you can always add /TRACE:ON so you can inspect the calls being made. Use wmic /? to see the aliasses.

C# executing cmd command not working

Can anybody suggest why the following code not returning system date?
ProcessStartInfo cmdInfo = new ProcessStartInfo("cmd.exe", "net time \\192.168.221.1");
cmdInfo.CreateNoWindow = true;
cmdInfo.RedirectStandardOutput = true;
cmdInfo.RedirectStandardError = true;
cmdInfo.UseShellExecute = false;
Process cmd = new Process();
cmd.StartInfo = cmdInfo;
var output = new StringBuilder();
var error = new StringBuilder();
cmd.OutputDataReceived += (o, e) => output.Append(e.Data);
cmd.ErrorDataReceived += (o, e) => error.Append(e.Data);
cmd.Start();
cmd.BeginOutputReadLine();
cmd.BeginErrorReadLine();
cmd.WaitForExit();
cmd.Close();
var s = output;
var d = error;
Output is
{Microsoft Windows [Version 6.1.7601]Copyright (c) 2009 Microsoft Corporation. All rights reserved.D:\TEST\TEST\bin\Debug>}
Try with this
ProcessStartInfo cmdInfo = new ProcessStartInfo("cmd.exe", "/C net time \\\\192.168.221.1");
You need to add the /C switch to catch the output of running command inside the CMD shell.
Also the backslash should be doubled or use the string Verbatim prefix #

Categories

Resources