CA1302:請勿於程式中定義地區設定專屬的字串

型別名稱

DoNotHardcodeLocaleSpecificStrings

CheckId

CA1302

分類

Microsoft.Globalization

中斷變更

中斷

原因

方法會使用字串常值 (String Literal),表示某些系統資料夾的路徑部分。

規則描述

System.Environment.SpecialFolder 列舉型別 (Enumeration) 包含參考特殊系統資料夾的成員。 這些資料夾的位置在不同的作業系統上可有不同的值,使用者可以變更某些位置,而且位置會當地語系化。 特殊資料夾的一個範例是系統資料夾。在 Windows XP 是 "C:\WINDOWS\system32",但在 Windows 2000 上則是 "C:\WINNT\system32"。 Environment.GetFolderPath 方法會傳回與 Environment.SpecialFolder 列舉相關聯的位置。 由 GetFolderPath 所傳回的位置會當地語系化,並且適用於目前執行中的電腦。

這項規則會將使用 GetFolderPath 方法所擷取的資料夾路徑,語彙基元化到不同的目錄層級。 每個字串常值會與語彙基元比較。 如果找到相符項目,則假設方法正在建置的字串會參考與此語彙基元關聯的系統位置。 針對可攜性和可當地語系化,請使用 GetFolderPath 方法而非字串常值,擷取特殊系統資料夾的位置。

如何修正違規

若要修正此規則的違規情形,請使用 GetFolderPath 方法擷取位置。

隱藏警告的時機

如果字串常值並未用於參考與 Environment.SpecialFolder 列舉關聯的其中一個系統位置,則您可以放心地隱藏這項規則的警告。

範例

下列範例會建置通用應用程式儲存資料夾的路徑,此資料夾會根據此規則產生三個警告。 此範例接著會使用 GetFolderPath 方法擷取路徑。

Imports System

Namespace GlobalizationLibrary

   Class WriteSpecialFolders

      Shared Sub Main()

         Dim string0 As String = "C:"

         ' Each of the following three strings violates the rule.
         Dim string1 As String = "\Documents and Settings"
         Dim string2 As String = "\All Users"
         Dim string3 As String = "\Application Data"
         Console.WriteLine(string0 & string1 & string2 & string3)

         ' The following statement satisfies the rule.
         Console.WriteLine(Environment.GetFolderPath( _ 
            Environment.SpecialFolder.CommonApplicationData))

      End Sub

   End Class

End Namespace
using System;

namespace GlobalizationLibrary
{
   class WriteSpecialFolders
   {
      static void Main()
      {
         string string0 = "C:";

         // Each of the following three strings violates the rule.
         string string1 = @"\Documents and Settings";
         string string2 = @"\All Users";
         string string3 = @"\Application Data";
         Console.WriteLine(string0 + string1 + string2 + string3);

         // The following statement satisfies the rule.
         Console.WriteLine(Environment.GetFolderPath(
            Environment.SpecialFolder.CommonApplicationData));
      }
   }
}

相關規則

CA1303:不要將常值當做已當地語系化的參數傳遞