次の方法で共有


ロケール固有の文字列をハードコーディングしないでください

更新 : 2007 年 11 月

TypeName

DoNotHardcodeLocaleSpecificStrings

CheckId

CA1302

カテゴリ

Microsoft.Globalization

互換性に影響する変更点

なし

原因

メソッドで、特殊なシステム フォルダのパスの一部を表すリテラル文字列を使用しています。

規則の説明

System.Environment.SpecialFolder 列挙体には、特殊なシステム フォルダを参照するメンバが含まれます。このフォルダの位置は、オペレーティング システムによって異なる場合、ユーザーが位置を変更する場合、および位置がローカライズされる場合があります。特殊なフォルダの例として、System フォルダがあります。Windows XP では "C:\WINDOWS\system32" ですが、Windows 2000 では "C:\WINNT\system32" です。Environment.GetFolderPath メソッドは、Environment.SpecialFolder 列挙体に関連付けられた位置を返します。GetFolderPath から返された位置は、現在実行されているコンピュータに合わせてローカライズされます。

この規則は、GetFolderPath メソッドを使用して取得したフォルダのパスを、別のディレクトリ レベルにトークン化します。各リテラル文字列はこのトークンと比較されます。一致するものが見つかった場合、メソッドによって、トークンに関連付けられたシステム フォルダを参照する文字列が構築されると想定されます。特殊なシステム フォルダの位置を取得するには、移植性と地域性を考慮して、リテラル文字列ではなく GetFolderPath メソッドを使用します。

違反の修正方法

この規則違反を修正するには、GetFolderPath メソッドを使用して位置を取得します。

警告を抑制する状況

Environment.SpecialFolder 列挙体に関連付けられたシステム フォルダのいずれかを参照するときに、リテラル文字列を使用していない場合は、この規則による警告を抑制しても安全です。

使用例

共通のアプリケーション データ フォルダのパスを構築する方法を次の例に示します。この規則によって 3 つの警告が生成されます。次に、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));
      }
   }
}