All rules
CA1839Performance Enabled by default: As suggestion

Use Environment.ProcessPath instead of Process.GetCurrentProcess().MainModule.FileName

Use Environment.ProcessPath instead of Process.GetCurrentProcess().MainModule.FileName

Microsoft docs

Description

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

  • It allocates a System.Diagnostics.Process and System.Diagnostics.ProcessModule instance, usually just to get the FileName.
  • The System.Diagnostics.Process instance needs to be disposed, which has a performance impact.
  • It's easy to forget to call System.Diagnostics.Process.Dispose on the System.Diagnostics.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. System.Environment.ProcessPath is available starting in .NET 6.

Cause

Using Process.GetCurrentProcess().MainModule.FileName for getting the path to the file that launched the process instead of System.Environment.ProcessPath.

How to fix violations

The violation can either be fixed manually, or, in some cases, using Quick Actions to fix code in Visual Studio.

The following two code snippets show a violation of the rule and how to fix it: A code fix is available for this rule in Visual Studio. To use it, position the cursor on the violation and press <kbd>Ctrl</kbd>+<kbd>.</kbd> (period). Choose Use 'Environment.ProcessPath' from the list of options that's presented. !Code fix for CA1839 - Use 'Environment.ProcessPath'

Example

using System.Diagnostics;

class MyClass
{
    void MyMethod()
    {
        string path = Process.GetCurrentProcess().MainModule.FileName; // Violation occurs
    }
}

When to suppress

It's safe to suppress a violation of this rule if you're not concerned about the performance impact from unnecessary allocation and eventual disposal of the System.Diagnostics.Process and System.Diagnostics.ProcessModule instances.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0