1

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.

Ian
  • 1,221
  • 1
  • 18
  • 30
Belcookies
  • 23
  • 6
  • Possible duplicate of [Adding a string to the verbatim string literal](https://stackoverflow.com/questions/10537578/adding-a-string-to-the-verbatim-string-literal). If you look at the answer to that question, it shows you a couple of ways to add a string value to literal string. You can ignore all the stuff about quotes! :) – Ian Sep 18 '18 at 12:55
  • 1
    Is there a reason you are trying those scripting shenanigans instead of using [Process.GetProcessesByName](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.getprocessesbyname?view=netframework-4.7.2)? – nvoigt Sep 18 '18 at 13:04

3 Answers3

2

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 ),
Developer
  • 66
  • 1
  • 6
2

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.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
1

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.

FvL
  • 36
  • 1
  • 4