Covers topics on the Microsoft Certification Exam for the .NET Framework (Exam 70-536, Microsoft .NET Framework - Application Development Foundation)

Tuesday, October 21, 2008

How do I retrieve information about the current process using C#?

I can think of many occasions when I have been diagnosing an issue on a customer machine and I find myself opening the task manager to gather valuable information about the application under question. If the customer will allow it, I will usually take the task manager one step further and use the Process Explorer from SysInternals.

But there has to be a better way, your application should be able to grab that information without using another application. And in fact it can by using the System.Diagnostics namespace. Conveniently this is also a requirement on the 70-536 exam in the "Manage system processes and monitor the performance of a .NET application by using the diagnostics functionality of the .NET Framework." section. Specifically the objective is to:

"Retrieve information about the current process"

This is made possible by the Process class within the System.Diagnostics class. Before we get into the code sample, it should be noted that a Process has a number of attributes. Many of these attributes are omitted to keep it short and sweet. Refer to the docs for the full list of Process attributes.

Current Process Info Example

using System;
using System.Diagnostics;

namespace CurrentProcessInfo
class Program
static void Main(string[] args)
//First lets get our parent process
Process my_process = Process.GetCurrentProcess();

// Now we'll spit out some pertinent info on our process
// Only a handful of the properties are referred to here,
// see the docs for the full list
Console.WriteLine("\nThe current process has the following attributes:");
Console.WriteLine("Process Name: " + my_process.ProcessName);
Console.WriteLine("Window Title: " + my_process.MainWindowTitle);
Console.WriteLine("Running on: " + my_process.MachineName);
Console.WriteLine("Priority: " + my_process.PriorityClass.ToString());
Console.WriteLine("Responding: " + my_process.Responding);
Console.WriteLine("Virtual Memory: " + my_process.VirtualMemorySize64);

Additional Resources
Process Class (Microsoft)
System.Diagnostics Namespace (Microsoft)

No comments:

Support This Site

LinkShare  Referral  Prg