分享方式:


CA1839:使用 'Environment.ProcessPath' 而非 'Process.GetCurrentProcess().MainModule.FileName

屬性
規則識別碼 CA1839
標題 使用 Environment.ProcessPath,而不是 Process.GetCurrentProcess()。MainModule.FileName
類別 效能
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 建議

原因

使用 Process.GetCurrentProcess().MainModule.FileName 取得啟動進程之檔案的路徑,而不是 Environment.ProcessPath

檔案描述

System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName 成本高昂:

  • 它會配置 ProcessProcessModule 實例,通常只是為了取得 FileName
  • 實例 Process 必須處置,這會影響效能。
  • 您可以輕鬆地忘記在 實例上 Process 呼叫 Dispose()
  • 如果除了 FileName 使用 Process 實例之外,沒有其他專案,則連結大小會藉由增加參考類型的圖表而不必要的成長。
  • 探索或尋找此 API 有點困難。

System.Environment.ProcessPath 會避免所有這些缺點,並產生相同的資訊。

注意

System.Environment.ProcessPath 從 .NET 6 開始提供。

如何修正違規

違規可以手動修正,或在某些情況下,使用快速動作修正 Visual Studio 中的程式碼。

下列兩個程式碼片段顯示違反規則,以及如何修正它:

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

提示

Visual Studio 中有一個程式碼修正程式碼可供此規則使用。 若要使用它,請將游標放在違規上,然後按 Ctrl + 。 (句號)。 從所呈現的選項清單中選擇 [使用 'Environment.ProcessPath' ]。

Code fix for CA1839 - Use 'Environment.ProcessPath'

隱藏警告的時機

如果您不擔心來自不必要的配置和最終處置 ProcessProcessModule 實例的效能影響,則隱藏此規則的違規是安全的。

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

#pragma warning disable CA1839
// The code that's violating the rule is on this line.
#pragma warning restore CA1839

若要停用檔案、資料夾或專案的規則,請在組態檔 中將其嚴重性設定為 。 none

[*.{cs,vb}]
dotnet_diagnostic.CA1839.severity = none

如需詳細資訊,請參閱 如何隱藏程式碼分析警告

另請參閱