Belcookies
Belcookies

Reputation: 33

How to insert a string into a literal string

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.

Upvotes: 1

Views: 128

Answers (3)

FvL
FvL

Reputation: 36

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.

Upvotes: 1

nvoigt
nvoigt

Reputation: 77285

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.

Upvotes: 2

Developer
Developer

Reputation: 66

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 ),

Upvotes: 2

Related Questions