I´m trying to make a program. that will find a programs PID number.
so far i got it to work with notepad.
Code:
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/C for /f \"tokens=1,2\" %a in " + "('Tasklist /fi \"imagename eq notepad.exe\" /nh') do #echo %b",
RedirectStandardOutput = true,
UseShellExecute = false,
}
};
Its not going to be a Notepad it was just for testing purposes.
I want it to be a string that stands there instead of notepad.
Like this
String myProgram = #"[insert program name]";
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/C for /f \"tokens=1,2\" %a in " + "('Tasklist /fi \"imagename eq MyProgram\" /nh') do #echo %b",
RedirectStandardOutput = true,
UseShellExecute = false,
}
};
I don't know how to change it from the text "notepad" to my string.
Maybe it can work?
Arguments = string.Format("/C for /f \"tokens=1,2\" %a in " + "('Tasklist /fi \"imagename eq {0}\" /nh') do #echo %b",myProgram ),
This will give you the PIDs of all running notepad instances:
foreach (var notepad in Process.GetProcessesByName("notepad"))
{
Console.WriteLine(notepad.Id);
}
There is no need to start a batch processor and fiddle with it's parameters.
Simplest way would be to use the string.Format shorthand:
string myProgram = #"[insert program name]";
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/C for /f \"tokens=1,2\" %a in ('Tasklist /fi \"imagename eq {myProgram}\" /nh') do #echo %b",
RedirectStandardOutput = true,
UseShellExecute = false,
}
};
Edit: Per Ian's suggestion, the $ shorthand operator for string.Format is only available in C# 6. This won't work for earlier versions.
Related
In windows, we can use
var startInfo = new System.Diagnostics.ProcessStartInfo
{
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
FileName = "cmd.exe",
Arguments = "adb devices"
};
process.StartInfo = startInfo;
process.Start();
Similar to that, Do we have anything to execute with terminal in Mac?
The only difference is you have to pass arguments with -c,
FileName = "/bin/bash",
Arguments = " -c \"" + argument + " \""
My question is literally, how do I execute a Shell command from my application. There is a similar Post, but that shows how to execute a script file and requires the path to that file.
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = command, // Path required here
Arguments = args,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
Why I want to pass the command as a string?
Because I want to interpolate it. Otherwise, I would have to create a script, with some input parameters. Since I'm not that good with Shell, I prefer the easy way.
Assume you want to run echo hello in bash, then
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "bash",
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
}
};
process.Start();
await process.StandardInput.WriteLineAsync("echo hello");
var output = await process.StandardOutput.ReadLineAsync();
Console.WriteLine(output);
I need to execute a batch file on remote server itself . I was using the below code as i found as an example but the batch file is getting executing on the application server itself and not on the remote server. If i need to create a log file using the batch file on remote server , it was throwing error stating file path cannot be found .Thanks for the help in advance
if (File.Exists(filePath))
{
var process = new Process();
var startInfo = new ProcessStartInfo
{
CreateNoWindow = true,
FileName = "cmd.exe",
Arguments = "/c \"\"" + filePath + "\"\"",
WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory,
//WorkingDirectory = workingdirectory,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true
};
process.StartInfo = startInfo;
process.Start();
//process.WaitForExit(30000);
string output = process.StandardOutput.ReadLine();
string errors = process.StandardError.ReadLine();
The work around for executing the batch file on remote server itself is to do a windows scheduler job and trigger the job by some c# code .Please find the below code to do that
string job = #"""\JobLocation\JobName""";
string server = #"XXXXXXXXXXX";
string user = #"Domian\XXXXXX";
string pwd = #"XXXXXXXXXXXXXXX";
string line = #" /run /tn " + job + " /s " + server + " /u " + user + " /p " + pwd;
var process = new Process();
var startInfo = new ProcessStartInfo
{
CreateNoWindow = true,
FileName = #"C:\WINDOWS\SYSTEM32\schtasks.exe",
WindowStyle = ProcessWindowStyle.Hidden,
Arguments = line,
//WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true
};
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
string output = process.StandardOutput.ReadLine();
string errors = process.StandardError.ReadLine();code here
i'm developing an application to get backup from my postgreSQL database with C#.
i,m using code below to execute and get out put from pg_dump.exe.
ProcessStartInfo startinfo = new ProcessStartInfo
{
FileName = "\"C:\\Program Files (x86)\\pgAdmin III\\1.16\\pg_dump.exe\"",
Arguments = "--host XXX.XXX.XXX.XXX --port 5432 --username \"USERNAME\" --no-password --format plain --verbose --file \"D:\\MYBACKUP.backup\" \"MYDBNAME\"",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
Process proc = new Process();
proc.StartInfo = startinfo;
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
var r = proc.StandardOutput.ReadLine();
}
proc.WaitForExit();
Console.WriteLine(proc.ExitCode);
Console.ReadLine();
but proc.StandardOutput.ReadLine always returns null!!!
i try to put pg_dump.exe output to a file with command propt like this:
C:\Program Files (x86)\pgAdmin III\1.16>pg_dump.exe > d:\log.txt
but again log.txt is empty!!
thanks in advance.
Replace RedirectStandardOutput with RedirectStandardError.
My working code is:
ProcessStartInfo startinfo = new ProcessStartInfo
{
FileName = "Path to pg_dump.exe",
Arguments = "Arguments",
UseShellExecute = false,
RedirectStandardError = true,
CreateNoWindow = true
};
using (Process process = Process.Start(startinfo))
{
using (StreamReader reader = process.StandardError)
{
StreamWriter sw = new StreamWriter(#"C:\log.txt");
sw.WriteLine(reader.ReadToEnd());
sw.Close();
}
}
I can in C# do the following:
var pSpawn = new Process
{
StartInfo = { WorkingDirectory = #"C:\temp", FileName = fileToRun, CreateNoWindow = true }
};
pSpawn.Start();
and this works fine.... however I am wondering if there is a way to run a command (ie: "dir /b") without having to encapsulate it in a batch file?
Just start the cmd.exe and pass the arguments required
var pSpawn = new Process
{
StartInfo =
{
WorkingDirectory = #"C:\temp",
FileName = "cmd.exe",
Arguments ="/K dir /b" }
};
pSpawn.Start();
I have added the parameter /K to leave the command window open so, it is possible to see the output of the command dir.
Of course I think that you are really interested to catch the output of the command.
In this case you could work with something like this:
StringBuilder sb = new StringBuilder();
var pSpawn = new Process
{
StartInfo =
{
WorkingDirectory = #"C:\temp",
FileName = "cmd.exe",
Arguments ="/c dir /b",
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false
}
};
pSpawn.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
pSpawn.Start();
pSpawn.BeginOutputReadLine();
pSpawn.WaitForExit();
Console.WriteLine(sb.ToString());
You can call something like this:
ProcessStartInfo info = new ProcessStartInfo("cmd.exe");
info.Arguments = "/c dir /b";
Process.Start(info);