建立桌面應用程式的附屬組件Creating Satellite Assemblies for Desktop Apps

資源檔在當地語系化的應用程式中扮演重要角色。Resource files play a central role in localized applications. 它們可讓應用程式以使用者自己的語言和文化特性顯示字串、影像和其他資料,以及在使用者自己的語言或文化特性的資源無法使用時提供替代資料。They enable an application to display strings, images, and other data in the user's own language and culture, and to provide alternate data if resources for the user's own language or culture are unavailable. .NET Framework 會使用中樞和支點模型來尋找並擷取當地語系化的資源。The .NET Framework uses a hub-and-spoke model to locate and retrieve localized resources. 中樞是主要組件,其中包含未當地語系化的可執行程式碼以及稱為中性或預設文化特性之單一文化特性的資源。The hub is the main assembly that contains the non-localizable executable code and the resources for a single culture, which is called the neutral or default culture. 預設文化特性是應用程式的後援文化特性;當地語系化的資源無法使用時會使用它。The default culture is the fallback culture for the application; it is used when no localized resources are available. 您使用 NeutralResourcesLanguageAttribute 屬性來指定應用程式之預設文化特性的文化特性。You use the NeutralResourcesLanguageAttribute attribute to designate the culture of the application's default culture. 每個支點都會連線至附屬組件,其中包含單一當地語系化文化特性但未包含任何程式碼的資源。Each spoke connects to a satellite assembly that contains the resources for a single localized culture but does not contain any code. 因為附屬組件不是主要組件的一部分,所以您可以輕鬆地更新或取代對應至特定文化特性的資源,而不需要取代應用程式的主要組件。Because the satellite assemblies are not part of the main assembly, you can easily update or replace resources that correspond to a specific culture without replacing the main assembly for the application.

注意

應用程式之預設文化特性的資源也可以儲存在附屬組件中。The resources of an application's default culture can also be stored in a satellite assembly. 若要這樣做,請將 UltimateResourceFallbackLocation.Satellite 的值指派給 NeutralResourcesLanguageAttribute 屬性。To do this, you assign the NeutralResourcesLanguageAttribute attribute a value of UltimateResourceFallbackLocation.Satellite.

附屬組件名稱和位置Satellite Assembly Name and Location

中樞和支點模型需要您將資源放入特定位置,以輕鬆地找到和使用它們。The hub-and-spoke model requires that you place resources in specific locations so that they can be easily located and used. 如果您未如預期編譯和命名資源,或未將它們放在正確位置,則 Common Language Runtime 會找不到它們,並改為使用預設文化特性的資源。If you do not compile and name resources as expected, or if you do not place them in the correct locations, the common language runtime will not be able to locate them and will use the resources of the default culture instead. ResourceManager 物件代表的 .NET Framework Resource Manager 是用來自動存取當地語系化資源。The .NET Framework Resource Manager, represented by a ResourceManager object, is used to automatically access localized resources. Resource Manager 需要下列各項:The Resource Manager requires the following:

  • 單一附屬組件必須包括特定文化特性的所有資源。A single satellite assembly must include all the resources for a particular culture. 換句話說,您應該將多個 .txt.resx檔案編譯成單一的二進位 .resources檔案。In other words, you should compile multiple .txt or .resx files into a single binary .resources file.

  • 在儲存該文化特性資源之每個當地語系化文化特性的應用程式目錄中,都必須有不同的子目錄。There must be a separate subdirectory in the application directory for each localized culture that stores that culture's resources. 子目錄名稱必須與文化特性名稱相同。The subdirectory name must be the same as the culture name. 或者,您可以在全域組件快取中儲存附屬組件。Alternately, you can store your satellite assemblies in the global assembly cache. 在此情況下,組件強式名稱的文化特性資訊元件必須指出其文化特性。In this case, the culture information component of the assembly's strong name must indicate its culture. (請參閱本主題稍後的在全域組件快取中安裝附屬組件一節)。(See the Installing Satellite Assemblies in the Global Assembly Cache section later in this topic.)

    注意

    如果您的應用程式包括子文化特性的資源,請將每個子文化特性放在應用程式目錄下的不同子目錄中。If your application includes resources for subcultures, place each subculture in a separate subdirectory under the application directory. 請不要將子文化特性放在其主要文化特性目錄的子目錄中。Do not place subcultures in subdirectories under their main culture's directory.

  • 附屬組件的名稱必須與應用程式相同,而且必須使用副檔名 ".resources.dll"。The satellite assembly must have the same name as the application, and must use the file name extension ".resources.dll". 例如,如果應用程式命名為example .exe,則每個附屬元件的名稱都應該是example. resources .dllFor example, if an application is named Example.exe, the name of each satellite assembly should be Example.resources.dll. 請注意,附屬組件名稱不會指出其資源檔的文化特性。Note that the satellite assembly name does not indicate the culture of its resource files. 不過,附屬組件會出現在確實指定文化特性的目錄中。However, the satellite assembly appears in a directory that does specify the culture.

  • 附屬組件文化特性的資訊必須包括在組件的中繼資料內。Information about the culture of the satellite assembly must be included in the assembly's metadata. 若要將文化特性名稱儲存在附屬組件的中繼資料內,請在使用組件連結器將資源內嵌在附屬組件時指定 /culture 選項。To store the culture name in the satellite assembly's metadata, you specify the /culture option when you use Assembly Linker to embed resources in the satellite assembly.

下圖顯示未在全域組件快取中安裝之應用程式的範例目錄結構和位置需求。The following illustration shows a sample directory structure and location requirements for applications that you are not installing in the global assembly cache. 副檔名為 .txt 和 .resources 的項目將不會隨附最終應用程式。The items with .txt and .resources extensions will not ship with the final application. 這些是用來建立最終附屬資源組件的中繼資源檔。These are the intermediate resource files used to create the final satellite resource assemblies. 在此範例中,您可以將 .resx 檔案取代為 .txt 檔案。In this example, you could substitute .resx files for the .txt files. 如需詳細資訊,請參閱封裝和部署資源For more information, see Packaging and Deploying Resources.

下圖顯示附屬組件目錄:The following image shows the satellite assembly directory:

使用當地語系化文化特性 (Culture) 子目錄的附屬組件目錄。

編譯附屬組件Compiling Satellite Assemblies

您可以使用資源檔產生器(resgen.exe) ,將包含資源的文字檔或 XML ( .resx)檔案編譯成二進位 .resources檔案。You use Resource File Generator (Resgen.exe) to compile text files or XML (.resx) files that contain resources to binary .resources files. 接著,您可以使用元件連結器(al.exe).resources檔案編譯成附屬元件。You then use Assembly Linker (Al.exe) to compile .resources files into satellite assemblies. Al.exe會從您指定的 .resources檔建立元件。Al.exe creates an assembly from the .resources files that you specify. 附屬組件只能包含資源,而不能包含任何可執行程式碼。Satellite assemblies can contain only resources; they cannot contain any executable code.

下列al.exe命令會從德文資源檔字串中建立應用程式的附屬元件 Example The following Al.exe command creates a satellite assembly for the application Example from the German resources file strings.de.resources.

al -target:lib -embed:strings.de.resources -culture:de -out:Example.resources.dll

下列al.exe命令也會建立應用程式的附屬元件 Example 從檔案字串. 刪除 .resourcesThe following Al.exe command also creates a satellite assembly for the application Example from the file strings.de.resources. /Template選項會使附屬元件繼承所有元件中繼資料,但父元件(例如 .dll)中的文化特性資訊除外。The /template option causes the satellite assembly to inherit all assembly metadata except for its culture information from the parent assembly (Example.dll).

al -target:lib -embed:strings.de.resources -culture:de -out:Example.resources.dll -template:Example.dll

下表將詳細說明在這些命令中使用的al.exe選項:The following table describes the Al.exe options used in these commands in more detail:

選項Option 描述Description
-target:lib 指定將附屬組件編譯成程式庫 (.dll) 檔案。Specifies that your satellite assembly is compiled to a library (.dll) file. 因為附屬組件未包含可執行程式碼,而且不是應用程式的主要組件,所以您必須將附屬組件儲存為 DLL。Because a satellite assembly does not contain executable code and is not an application's main assembly, you must save satellite assemblies as DLLs.
-embed:strings.de.resources al.exe編譯元件時,指定要內嵌的資源檔名稱。Specifies the name of the resource file to embed when Al.exe compiles the assembly. 您可以在附屬組件中內嵌多個 .resources 檔案;但是,如果您遵循中樞和支點模型,則必須為每個文化特性編譯一個附屬組件。You can embed multiple .resources files in a satellite assembly, but if you are following the hub-and-spoke model, you must compile one satellite assembly for each culture. 不過,您可以為字串和物件建立個別的 .resources 檔案。However, you can create separate .resources files for strings and objects.
-culture:de 指定要編譯之資源的文化特性。Specifies the culture of the resource to compile. Common Language Runtime 在搜尋所指定文化特性的資源時會使用這項資訊。The common language runtime uses this information when it searches for the resources for a specified culture. 如果您省略這個選項, al.exe仍然會編譯資源,但當使用者要求時,執行時間將無法找到它。If you omit this option, Al.exe will still compile the resource, but the runtime will not be able to find it when a user requests it.
-out:Example.resources.dll 指定輸出檔案的名稱。Specifies the name of the output file. 名稱必須遵循命名標準 <基底名稱>.resources.<副檔名>,其中 <基底名稱> 為主要組件的名稱,<副檔名> 則為有效的副檔名 (例如 .dll)。The name must follow the naming standard baseName.resources.extension, where baseName is the name of the main assembly and extension is a valid file name extension (such as .dll). 請注意,執行階段無法根據輸出檔名稱來判斷附屬組件的文化特性;您必須使用 /culture 選項來指定它。Note that the runtime is not able to determine the culture of a satellite assembly based on its output file name; you must use the /culture option to specify it.
-template:Example.dll 指定附屬組件要從中繼承所有組件中繼資料的組件,但不包括文化特性欄位。Specifies an assembly from which the satellite assembly will inherit all assembly metadata except the culture field. 只有在您指定的組件具有強式名稱時,此選項才會影響附屬組件。This option affects satellite assemblies only if you specify an assembly that has a strong name.

如需al.exe可用選項的完整清單,請參閱元件連結器(al.exe)For a complete list of options available with Al.exe, see Assembly Linker (Al.exe).

附屬組件:範例Satellite Assemblies: An Example

下列簡單 "Hello world" 範例會顯示包含當地語系化問候語的訊息方塊。The following is a simple "Hello world" example that displays a message box containing a localized greeting. 此範例包括英文 (美國)、法文 (法國) 和俄文 (俄國) 文化特性的資源,而其後援文化特性是英文。The example includes resources for the English (United States), French (France), and Russian (Russia) cultures, and its fallback culture is English. 若要建立範例,請執行下列動作:To create the example, do the following:

  1. 建立名為 [問候語] 或 [問候語] 的資源檔,以包含預設文化特性的資源。Create a resource file named Greeting.resx or Greeting.txt to contain the resource for the default culture. 將名為 HelloString 且其值為 "Hello world!" 的單一字串儲存Store a single string named HelloString whose value is "Hello world!" 在此檔案中。in this file.

  2. 若要指出英文 (en) 是應用程式的預設文化特性,請將下列 System.Resources.NeutralResourcesLanguageAttribute 屬性新增至應用程式的 AssemblyInfo 檔案或將編譯為應用程式主要組件的主要原始程式碼檔案。To indicate that English (en) is the application's default culture, add the following System.Resources.NeutralResourcesLanguageAttribute attribute to the application's AssemblyInfo file or to the main source code file that will be compiled into the application's main assembly.

    [assembly: NeutralResourcesLanguageAttribute("en")]
    
    <Assembly: NeutralResourcesLanguageAttribute("en")>
    
  3. 將其他文化特性 (en-US、fr-FR 和 ru-RU) 的支援新增至應用程式,如下所示:Add support for additional cultures (en-US, fr-FR, and ru-RU) to the application as follows:

    • 若要支援 en-us 或英文(美國)文化特性,請建立名為 en-US 的資源 檔,並在其中儲存名為 HelloString 的單一字串,其值為 "Hi world!"。To support the en-US or English (United States) culture, create a resource file named Greeting.en-US.resx or Greeting.en-US.txt, and store in it a single string named HelloString whose value is "Hi world!".

    • 若要支援 fr-fr 或法文(法國)文化特性,請建立名為Greeting.fr的資源檔,或Greeting.fr-fr.txt .txt,然後將名為 HelloString 的單一字串儲存在其中,其值為 "Salut tout le monde!"。To support the fr-FR or French (France) culture, create a resource file named Greeting.fr-FR.resx or Greeting.fr-FR.txt, and store in it a single string named HelloString whose value is "Salut tout le monde!".

    • 若要支援 ru-RU 或俄文(俄羅斯)文化特性,請建立名為Greeting.ru的資源檔,或Greeting.ru-ru.txt,並在其中儲存名為 HelloString 的單一字串,其值為 "Всемпривет!"。To support the ru-RU or Russian (Russia) culture, create a resource file named Greeting.ru-RU.resx or Greeting.ru-RU.txt, and store in it a single string named HelloString whose value is "Всем привет!".

  4. 使用resgen.exe ,將每個文字或 XML 資源檔編譯成二進位 .resources檔案。Use Resgen.exe to compile each text or XML resource file to a binary .resources file. 輸出是一組檔案,其根檔案名與 .resx.txt檔案相同,但副檔名為 .resourcesThe output is a set of files that have the same root file name as the .resx or .txt files, but a .resources extension. 如果您使用 Visual Studio 建立範例,則會自動處理編譯程序。If you create the example with Visual Studio, the compilation process is handled automatically. 如果您不是使用 Visual Studio,請執行下列命令,將 .resx檔案編譯為 .resources檔案:If you aren't using Visual Studio, run the following commands to compile the .resx files into .resources files:

    resgen Greeting.resx
    resgen Greeting.en-us.resx
    resgen Greeting.fr-FR.resx
    resgen Greeting.ru-RU.resx
    

    如果您的資源是在文字檔中,而不是 XML 檔案,請以 .txt取代 .resx副檔名。If your resources are in text files instead of XML files, replace the .resx extension with .txt.

  5. 將下列原始程式碼與預設文化特性的資源編譯為應用程式的主要組件:Compile the following source code along with the resources for the default culture into the application's main assembly:

    重要

    如果您使用命令列建立範例而非 Visual Studio,則應該將 ResourceManager 類別建構函式的呼叫修改為下列:ResourceManager rm = new ResourceManager("Greetings", typeof(Example).Assembly);If you are using the command line rather than Visual Studio to create the example, you should modify the call to the ResourceManager class constructor to the following: ResourceManager rm = new ResourceManager("Greetings", typeof(Example).Assembly);

    using System;
    using System.Globalization;
    using System.Reflection;
    using System.Resources;
    using System.Threading;
    using System.Windows.Forms;
    
    class Example
    {
       static void Main()
       {
          // Create array of supported cultures
          string[] cultures = {"en-CA", "en-US", "fr-FR", "ru-RU"};
          Random rnd = new Random();
          int cultureNdx = rnd.Next(0, cultures.Length);
          CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;
    
          try {
             CultureInfo newCulture = new CultureInfo(cultures[cultureNdx]);
             Thread.CurrentThread.CurrentCulture = newCulture;
             Thread.CurrentThread.CurrentUICulture = newCulture;
             ResourceManager rm = new ResourceManager("Example.Greetings", 
                                                      typeof(Example).Assembly); 
             string greeting = String.Format("The current culture is {0}.\n{1}",
                                             Thread.CurrentThread.CurrentUICulture.Name,
                                             rm.GetString("HelloString"));
    
             MessageBox.Show(greeting);
          }
          catch (CultureNotFoundException e) {
             Console.WriteLine("Unable to instantiate culture {0}", e.InvalidCultureName);
          }
          finally {
             Thread.CurrentThread.CurrentCulture = originalCulture;
             Thread.CurrentThread.CurrentUICulture = originalCulture;
          }
       }
    }
    
    Imports System.Globalization
    Imports System.Resources
    Imports System.Threading
    
    Module Module1
    
       Sub Main()
          ' Create array of supported cultures
          Dim cultures() As String = {"en-CA", "en-US", "fr-FR", "ru-RU" }
          Dim rnd As New Random()
          Dim cultureNdx As Integer = rnd.Next(0, cultures.Length)
          Dim originalCulture As CultureInfo = Thread.CurrentThread.CurrentCulture
    
          Try
             Dim newCulture As New CultureInfo(cultures(cultureNdx))
             Thread.CurrentThread.CurrentCulture = newCulture
             Thread.CurrentThread.CurrentUICulture = newCulture
             Dim greeting As String = String.Format("The current culture is {0}.{1}{2}",
                                                    Thread.CurrentThread.CurrentUICulture.Name,
                                                    vbCrLf, My.Resources.Greetings.HelloString)
    
             MsgBox(greeting)
          Catch e As CultureNotFoundException
             Console.WriteLine("Unable to instantiate culture {0}", e.InvalidCultureName)
          Finally
             Thread.CurrentThread.CurrentCulture = originalCulture
             Thread.CurrentThread.CurrentUICulture = originalCulture
          End Try
       End Sub
    End Module
    

    如果應用程式的名稱為範例,而您是從命令列進行編譯,則C#編譯器的命令為:If the application is named Example and you are compiling from the command-line, the command for the C# compiler is:

    csc Example.cs -res:Greeting.resources
    

    對應的 Visual Basic 編譯器命令為:The corresponding Visual Basic compiler command is:

    vbc Example.vb -res:Greeting.resources
    
  6. 在應用程式所支援之每個當地語系化文化特性的主要應用程式目錄中,建立子目錄。Create a subdirectory in the main application directory for each localized culture supported by the application. 您應該建立en-usFR-FRru ru 的子目錄。You should create an en-US, an fr-FR, and an ru-RU subdirectory. Visual Studio 會在編譯程序時自動建立這些子目錄。Visual Studio creates these subdirectories automatically as part of the compilation process.

  7. 將個別文化特性特定 .resources檔案內嵌到附屬元件,並將它們儲存到適當的目錄。Embed the individual culture-specific .resources files into satellite assemblies and save them to the appropriate directory. 針對每個 .resources檔案執行此動作的命令為:The command to do this for each .resources file is:

    al -target:lib -embed:Greeting.culture.resources -culture:culture -out:culture\Example.resources.dll
    

    其中 culture 是附屬組件會包含其資源的文化特性名稱。where culture is the name of the culture whose resources the satellite assembly contains. Visual Studio 會自動處理這個程序。Visual Studio handles this process automatically.

您接著可以執行此範例。You can then run the example. 它會隨機讓其中一個支援的文化特性成為目前文化特性,並顯示當地語系化的問候語。It will randomly make one of the supported cultures the current culture and display a localized greeting.

在全域組件快取中安裝附屬組件Installing Satellite Assemblies in the Global Assembly Cache

您可以將組件安裝在全域組件快取中,而不是在本機應用程式子目錄中安裝組件。Instead of installing assemblies in a local application subdirectory, you can install them in the global assembly cache. 如果您有供多個應用程式使用的類別庫和類別庫資源組件,則這特別有用。This is particularly useful if you have class libraries and class library resource assemblies that are used by multiple applications.

在全域組件快取中安裝組件時,需要組件具有強式名稱。Installing assemblies in the global assembly cache requires that they have strong names. 強式名稱組件會使用有效的公開/私密金鑰組進行簽署。Strong-named assemblies are signed with a valid public/private key pair. 它們包含執行階段用來判斷要用來滿足繫結要求之組件的版本資訊。They contain version information that the runtime uses to determine which assembly to use to satisfy a binding request. 如需強式名稱和版本控制的詳細資訊,請參閱組件版本控制For more information about strong names and versioning, see Assembly Versioning. 如需強式名稱的詳細資訊,請參閱強式名稱的組件For more information about strong names, see Strong-Named Assemblies.

當您開發應用程式時,可能無法存取最終公開/私密金鑰組。When you are developing an application, it is unlikely that you will have access to the final public/private key pair. 若要在全域組件快取中安裝附屬組件,並確認它的運作正常,您可以使用稱為延遲簽署的技術。In order to install a satellite assembly in the global assembly cache and ensure that it works as expected, you can use a technique called delayed signing. 當您延遲簽署組件時,請在建置時間於檔案中保留強式名稱簽章的空間。When you delay sign an assembly, at build time you reserve space in the file for the strong name signature. 有最終公開/私密金鑰組可用時,會將實際簽署延遲到稍後。The actual signing is delayed until later, when the final public/private key pair is available. 如需延遲簽署的詳細資訊,請參閱延遲簽署組件For more information about delayed signing, see Delay Signing an Assembly.

取得公開金鑰Obtaining the Public Key

若要延遲簽署組件,您必須具有公開金鑰的存取權。To delay sign an assembly, you must have access to the public key. 您可以從公司中進行最後簽署的組織中取得實際公開金鑰,或使用強式名稱工具 (Sn.exe) 建立公開金鑰。You can either obtain the real public key from the organization in your company that will do the eventual signing, or create a public key by using the Strong Name Tool (Sn.exe).

下列sn.exe命令會建立測試公開/私密金鑰組。The following Sn.exe command creates a test public/private key pair. – K選項指定sn.exe應建立新的金鑰組,並將它儲存在名為testkeypair.snk的檔案中。The –k option specifies that Sn.exe should create a new key pair and save it in a file named TestKeyPair.snk.

sn –k TestKeyPair.snk

您可以從包含測試金鑰組的檔案中擷取公開金鑰。You can extract the public key from the file that contains the test key pair. 下列命令會從testkeypair.snk解壓縮公開金鑰,並將它儲存在PublicKey中:The following command extracts the public key from TestKeyPair.snk and saves it in PublicKey.snk:

sn –p TestKeyPair.snk PublicKey.snk

延遲簽署組件Delay Signing an Assembly

在您取得或建立公開金鑰之後,請使用組件連結器 (Al.exe) 編譯組件,並指定延遲簽署。After you obtain or create the public key, you use the Assembly Linker (Al.exe) to compile the assembly and specify delayed signing.

下列al.exe命令會針對從字串. ja-jp檔案 StringLibrary 的應用程式,建立強式名稱的附屬元件:The following Al.exe command creates a strong-named satellite assembly for the application StringLibrary from the strings.ja.resources file:

al -target:lib -embed:strings.ja.resources -culture:ja -out:StringLibrary.resources.dll -delay+ -keyfile:PublicKey.snk

選項指定組件連結器應該延遲簽署組件。The -delay+ option specifies that the Assembly Linker should delay sign the assembly. -keyfile 選項指定金鑰檔名稱,其中包含要用來延遲簽署組件的公開金鑰。The -keyfile option specifies the name of the key file that contains the public key to use to delay sign the assembly.

重新簽署組件Re-signing an Assembly

部署您的應用程式之前,必須使用實際金鑰組來重新簽署延遲簽署的附屬組件。Before you deploy your application, you must re-sign the delay signed satellite assembly with the real key pair. 您可以使用sn.exe來執行這項操作。You can do this by using Sn.exe.

下列sn.exe命令會使用儲存在RealKeyPair檔案中的金鑰組來簽署StringLibraryThe following Sn.exe command signs StringLibrary.resources.dll with the key pair stored in the file RealKeyPair.snk. –R 選項指定要重新簽署先前簽署的組件還是延遲簽署的組件。The –R option specifies that a previously signed or delay signed assembly is to be re-signed.

sn –R StringLibrary.resources.dll RealKeyPair.snk

在全域組件快取中安裝附屬組件Installing a Satellite Assembly in the Global Assembly Cache

執行階段在資源後援程序中搜尋資源時,會先尋找全域組件快取When the runtime searches for resources in the resource fallback process, it looks in the global assembly cache first. (如需詳細資訊,請參閱封裝和部署資源主題的「資源回退程式」一節)。一旦使用強式名稱簽署附屬元件,就可以使用全域組件快取工具(Gacutil),將它安裝在全域組件快取中。(For more information, see the "Resource Fallback Process" section of the Packaging and Deploying Resources topic.) As soon as a satellite assembly is signed with a strong name, it can be installed in the global assembly cache by using the Global Assembly Cache Tool (Gacutil.exe).

下列Gacutil命令會在全域組件快取中安裝StringLibraryThe following Gacutil.exe command installs StringLibrary.resources.dll* in the global assembly cache:

gacutil -i:StringLibrary.resources.dll

/I選項指定Gacutil應該將指定的元件安裝到全域組件快取中。The /i option specifies that Gacutil.exe should install the specified assembly into the global assembly cache. 在快取中安裝附屬組件之後,其所含的資源可供設計成使用附屬組件的所有應用程式使用。After the satellite assembly is installed in the cache, the resources it contains become available to all applications that are designed to use the satellite assembly.

全域組件快取中的資源:範例Resources in the Global Assembly Cache: An Example

下列範例會使用 .NET Framework 類別庫中的方法,從資源檔擷取並傳回當地語系化的問候。The following example uses a method in a .NET Framework class library to extract and return a localized greeting from a resource file. 程式庫和其資源都會註冊在全域組件快取中。The library and its resources are registered in the global assembly cache. 此範例包括英文 (美國)、法文 (法國)、俄文 (俄國) 和英文文化特性的資源。The example includes resources for the English (United States), French (France), Russian (Russia), and English cultures. 英文是預設文化特性;其資源儲存在主要組件中。English is the default culture; its resources are stored in the main assembly. 此範例一開始會使用公開金鑰來延遲簽署程式庫和其附屬組件,然後使用公開/私密金鑰組來重新簽署它們。The example initially delay signs the library and its satellite assemblies with a public key, then re-signs them with a public/private key pair. 若要建立範例,請執行下列動作:To create the example, do the following:

  1. 如果您不是使用 Visual Studio,請使用下列強式名稱工具(sn.exe)命令來建立名為ResKey的公開/私密金鑰組:If you are not using Visual Studio, use the following Strong Name Tool (Sn.exe) command to create a public/private key pair named ResKey.snk:

    sn –k ResKey.snk
    

    如果您使用 Visual Studio,請使用專案 [屬性] 對話方塊的 [簽署] 索引標籤來產生金鑰檔。If you are using Visual Studio, use the Signing tab of the project Properties dialog box to generate the key file.

  2. 使用下列強式名稱工具(sn.exe)命令來建立名為PublicKey的公用金鑰檔案:Use the following Strong Name Tool (Sn.exe) command to create a public key file named PublicKey.snk:

    sn –p ResKey.snk PublicKey.snk
    
  3. 建立名為string .resx的資源檔,以包含預設文化特性的資源。Create a resource file named Strings.resx to contain the resource for the default culture. 將名為 Greeting 且其值為 "How do you do?" 的單一字串儲存Store a single string named Greeting whose value is "How do you do?" 在該檔案中。in that file.

  4. 若要指出 "en" 是應用程式的預設文化特性,請將下列 System.Resources.NeutralResourcesLanguageAttribute 屬性新增至應用程式的 AssemblyInfo 檔案或將編譯為應用程式主要組件的主要原始程式碼檔案:To indicate that "en" is the application's default culture, add the following System.Resources.NeutralResourcesLanguageAttribute attribute to the application's AssemblyInfo file or to the main source code file that will be compiled into the application's main assembly:

    [assembly:NeutralResourcesLanguageAttribute("en")]
    
    <Assembly:NeutralResourcesLanguageAttribute("en")>
    
  5. 將其他文化特性 (en-US、fr-FR 和 ru-RU 文化特性) 的支援新增至應用程式,如下所示:Add support for additional cultures (the en-US, fr-FR, and ru-RU cultures) to the application as follows:

    • 若要支援 "en-us" 或英文(美國)文化特性,請建立名為en-US 的資源檔,並在其中儲存名為 Greeting 的單一字串,其值為 "Hello!"。To support the "en-US" or English (United States) culture, create a resource file named Strings.en-US.resx or Strings.en-US.txt, and store in it a single string named Greeting whose value is "Hello!".

    • 若要支援 "fr-fr" 或法文(法國)文化特性,請建立名為Strings.frStrings.fr-fr.txt的資源檔,並在其中儲存名為 Greeting 的單一字串,其值為 "Bon 日記!"。To support the "fr-FR" or French (France) culture, create a resource file named Strings.fr-FR.resx or Strings.fr-FR.txt and store in it a single string named Greeting whose value is "Bon jour!".

    • 若要支援「ru-RU」或俄文(俄羅斯)文化特性,請建立名為Strings.ru的資源檔,或Strings.ru-ru.txt ,並在其中儲存名為 Greeting 的單一字串,其值為 "Привет!"。To support the "ru-RU" or Russian (Russia) culture, create a resource file named Strings.ru-RU.resx or Strings.ru-RU.txt and store in it a single string named Greeting whose value is "Привет!".

  6. 使用 Resgen.exe,將每一個文字或 XML 資源檔編譯成二進位 .resources 檔案。Use Resgen.exe to compile each text or XML resource file to a binary .resources file. 輸出是一組檔案,其根檔案名與 .resx.txt檔案相同,但副檔名為 .resourcesThe output is a set of files that have the same root file name as the .resx or .txt files, but a .resources extension. 如果您使用 Visual Studio 建立範例,則會自動處理編譯程序。If you create the example with Visual Studio, the compilation process is handled automatically. 如果您不是使用 Visual Studio,請執行下列命令,將 .resx檔案編譯為 .resources檔案:If you aren't using Visual Studio, run the following command to compile the .resx files into .resources files:

    resgen filename
    

    其中filename.resx或文字檔的選擇性路徑、檔案名和副檔名。Where filename is the optional path, file name, and extension of the .resx or text file.

  7. StringLibrary的下列原始程式碼和預設文化特性的資源,編譯成名為StringLibrary的延遲簽署程式庫元件:Compile the following source code for StringLibrary.vb or StringLibrary.cs along with the resources for the default culture into a delay signed library assembly named StringLibrary.dll:

    重要

    如果您使用命令列而非 Visual Studio 來建立範例,則應該將 ResourceManager 類別建構函式的呼叫修改為 ResourceManager rm = new ResourceManager("Strings", typeof(Example).Assembly);If you are using the command line rather than Visual Studio to create the example, you should modify the call to the ResourceManager class constructor to ResourceManager rm = new ResourceManager("Strings", typeof(Example).Assembly);.

    using System;
    using System.Globalization;
    using System.Reflection;
    using System.Resources;
    using System.Threading;
    
    [assembly:NeutralResourcesLanguageAttribute("en")]
    
    public class StringLibrary
    {
       public string GetGreeting()
       {
          ResourceManager rm = new ResourceManager("Strings", 
                               Assembly.GetAssembly(typeof(StringLibrary)));
          string greeting = rm.GetString("Greeting");
          return greeting;
       }
    }
    
    Imports System.Globalization
    Imports System.Reflection
    Imports System.Resources
    Imports System.Threading
    
    <Assembly:NeutralResourcesLanguageAttribute("en")>
    
    Public Class StringLibrary
       Public Function GetGreeting() As String
          Dim rm As New ResourceManager("Strings", _
                                        Assembly.GetAssembly(GetType(StringLibrary)))
          Dim greeting As String = rm.GetString("Greeting")
          Return greeting
       End Function
    End Class
    

    C# 編譯器的命令是:The command for the C# compiler is:

    csc -t:library -resource:Strings.resources -delaysign+ -keyfile:publickey.snk StringLibrary.cs
    

    對應的 Visual Basic 編譯器命令為:The corresponding Visual Basic compiler command is:

    vbc -t:library -resource:Strings.resources -delaysign+ -keyfile:publickey.snk StringLibrary.vb
    
  8. 在應用程式所支援之每個當地語系化文化特性的主要應用程式目錄中,建立子目錄。Create a subdirectory in the main application directory for each localized culture supported by the application. 您應該建立en-usFR-FRru ru 的子目錄。You should create an en-US, an fr-FR, and an ru-RU subdirectory. Visual Studio 會在編譯程序時自動建立這些子目錄。Visual Studio creates these subdirectories automatically as part of the compilation process. 因為所有附屬組件都有相同的檔案名稱,所以使用子目錄來儲存個別文化特性特定附屬組件,直到使用公開/私密金鑰組簽署它們為止。Because all satellite assemblies have the same file name, the subdirectories are used to store individual culture-specific satellite assemblies until they are signed with a public/private key pair.

  9. 將個別文化特性特定 .resources檔案內嵌到延遲簽署的附屬元件,並將它們儲存到適當的目錄。Embed the individual culture-specific .resources files into delay signed satellite assemblies and save them to the appropriate directory. 針對每個 .resources檔案執行此動作的命令為:The command to do this for each .resources file is:

    al -target:lib -embed:Strings.culture.resources -culture:culture -out:culture\StringLibrary.resources.dll -delay+ -keyfile:publickey.snk
    

    其中 culture 是文化特性的名稱。where culture is the name of a culture. 在此範例中,文化特性名稱是 en-US、fr-FR 和 ru-RU。In this example, the culture names are en-US, fr-FR, and ru-RU.

  10. 使用強式名稱工具(sn.exe)重新簽署StringLibrary ,如下所示:Re-sign StringLibrary.dll by using the Strong Name Tool (Sn.exe) as follows:

    sn –R StringLibrary.dll RealKeyPair.snk
    
  11. 重新簽署個別附屬組件。Re-sign the individual satellite assemblies. 若要這樣做,請使用每個附屬組件的強式名稱工具 (Sn.exe),如下所示:To do this, use the Strong Name Tool (Sn.exe) as follows for each satellite assembly:

    sn –R StringLibrary.resources.dll RealKeyPair.snk
    
  12. 使用下列命令,在全域組件快取中註冊StringLibrary和其每個附屬元件:Register StringLibrary.dll and each of its satellite assemblies in the global assembly cache by using the following command:

    gacutil -i filename
    

    其中 <檔案名稱> 是要註冊之檔案的名稱。where filename is the name of the file to register.

  13. 如果您使用 Visual Studio,請建立名為 Example的新主控台應用程式專案,並在其中新增StringLibrary的參考和下列原始程式碼,然後進行編譯。If you are using Visual Studio, create a new Console Application project named Example, add a reference to StringLibrary.dll and the following source code to it, and compile.

    using System;
    using System.Globalization;
    using System.Threading;
    
    public class Example
    {
       public static void Main()
       {
          string[] cultureNames = { "en-GB", "en-US", "fr-FR", "ru-RU" };
          Random rnd = new Random();
          string cultureName = cultureNames[rnd.Next(0, cultureNames.Length)]; 
          Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultureName);
          Console.WriteLine("The current UI culture is {0}", 
                            Thread.CurrentThread.CurrentUICulture.Name);
          StringLibrary strLib = new StringLibrary();
          string greeting = strLib.GetGreeting();
          Console.WriteLine(greeting);
       }
    }
    
    Imports System.Globalization
    Imports System.Threading
    
    Module Example
       Public Sub Main()
          Dim cultureNames() As String = { "en-GB", "en-US", "fr-FR", "ru-RU" }
          Dim rnd As New Random()
          Dim cultureName As String = cultureNames(rnd.Next(0, cultureNames.Length)) 
          Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultureName)
          Console.WriteLine("The current UI culture is {0}", 
                            Thread.CurrentThread.CurrentUICulture.Name)
          Dim strLib As New StringLibrary()
          Dim greeting As String = strLib.GetGreeting()
          Console.WriteLine(greeting)
       End Sub
    End Module
    

    若要從命令列進行編譯,請針對 C# 編譯器使用下列命令:To compile from the command line, use the following command for the C# compiler:

    csc Example.cs -r:StringLibrary.dll
    

    Visual Basic 編譯器的命令列為:The command line for the Visual Basic compiler is:

    vbc Example.vb -r:StringLibrary.dll
    
  14. 執行範例 .exeRun Example.exe.

請參閱See also