1) Process[] csProcess is not static. Frankly, modules shouldn't be either.
2) You can't use var outside of a method. Use ProcessModuleCollection instead.
Static variables, methods, etc. are scoped to the application, whereas member (non-static variables, methods, etc.) belong to the instance of the class/struct that you create.
This gives more info on when static variables are instantiated:
When do static variables get initialized in C#?
You could refactor your code like this if you wanted to keep those variables global to the application:
public class Program
{
static Process csProcess;
static ProcessModuleCollection modules;
static void Main(string[] args)
{
csProcess = Process.GetProcessesByName("notepad").FirstOrDefault();
if (csProcess == null) { return; } // notepad isn't running
modules = csProcess.Modules;
foreach (ProcessModule module in modules)
{
if (module.ModuleName == "client.dll")
{
// do stuff
}
}
}
}
The current answer takes the first notepad process it finds, and loops through its modules. If you want to check every notepad process that it finds, you need to remove .First()
, change Process
to Process[]
, and loop through: foreach (var process in csProcess) { //code }
But I'd advise learning the difference between static and instance variables ASAP.