Skip to content

Files

Latest commit

 

History

History
31 lines (20 loc) · 1.02 KB

File metadata and controls

31 lines (20 loc) · 1.02 KB

Pattern: Use of Process.GetCurrentProcess().MainModule.FileName

Issue: -

Description

System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName is expensive:

  • It allocates a Process and ProcessModule instance, usually just to get the FileName.
  • The Process instance needs to be disposed, which has a performance impact.
  • It's easy to forget to call Dispose() on the Process instance.
  • If nothing else besides FileName uses the Process instance, then the linked size grows unnecessarily by increasing the graph of types referenced.
  • It is somewhat difficult to discover or find this API.

System.Environment.ProcessPath avoids all of these downsides and produces the same information.

Example of incorrect code:

string path = Process.GetCurrentProcess().MainModule.FileName;

Example of correct code:

string path = System.Environment.ProcessPath;

Further Reading