Using Process.GetCurrentProcess().MainModule.FileName
for getting the path to the file that launched the process instead of Environment.ProcessPath.
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
is expensive:
FileName
.FileName
uses the Process
instance, then the linked size grows unnecessarily by increasing the graph of types referenced.System.Environment.ProcessPath
avoids all of these downsides and produces the same information.
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 Class
using 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 Class
Tip
A code fix is available for this rule in Visual Studio. To use it, position the cursor on the violation and press Ctrl+. (period). Choose Use 'Environment.ProcessPath' from the list of options that's presented.
When to suppress warningsIt'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 Process and ProcessModule instances.
Suppress a warningIf 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 CA1839
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1839.severity = none
For more information, see How to suppress code analysis warnings.
See alsoRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4