Cause
Using Process.GetCurrentProcess().MainModule.FileName for getting the path to the file that launched the process instead of System.Environment.ProcessPath.
Rule 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
FileNameuses theProcessinstance, 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.
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:
using System.Diagnostics;
class MyClass
{
void MyMethod()
{
string path = Process.GetCurrentProcess().MainModule.FileName; // Violation occurs
}
}Imports System.Diagnostics
Class MyClass
Private Sub MyMethod()
Dim path As String = Process.GetCurrentProcess().MainModule.FileName ' Violation occurs.
End Function
End Classusing System.Diagnostics;
class MyClass
{
void MyMethod()
{
string path = System.Environment.ProcessPath; // Violation fixed
}
}Imports System.Diagnostics
Class MyClass
Private Sub MyMethod()
Dim path As String = System.Environment.ProcessPath ' Violation fixed.
End Function
End ClassWhen to suppress warnings
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.
Suppress a warning
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable CA1839
// The code that's violating the rule is on this line.
#pragma warning restore CA1839To disable the rule for a file, folder, or project, set its severity to none in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1839.severity = noneFor more information, see How to suppress code analysis warnings.