- 右鍵點擊您在
Solution Explorer
Project
。
- 選擇添加 - >新建項目 - >資源 文件。
- 將其命名爲
Resources.en-us.resx
。 (替換 'EN-US' 適當 代碼)
- 單擊添加
- 將其拖到
Properties
文件夾。
- 開放Resources.en-us.resx和改變它的
Access Modifier
到Public
。
- 添加您的字符串。
- 重複每個文化你需要支持 。
在構建VS將的.resx文件轉換爲.resource文件,並建立包裝類爲您服務。然後您可以通過名稱空間YourAssembly.Properties.Resources
進行訪問。
使用此使用語句。
using YourAssembly.Properties;
你可以用這樣的屬性修飾:
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "MyStringName")]
注:我使用的屬性文件夾中的一致性。要使用App_GlobalResources將您的.resx文件移動到那裏,並更改您的使用語句以匹配目錄名稱。就像這樣:
using YourAssembly.App_GlobalResources;
編輯:你可以得到強類型資源名稱最接近的將是做這樣的事情:
public class ResourceNames
{
public const string EmailRequired = "EmailRequired";
}
然後,您可以用這樣的屬性裝飾。
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = ResourceNames.EmailRequired)]
要啓用自動客戶培養檢測添加globalizationsection到的web.config文件。
<configuration>
<system.web>
<globalization enableClientBasedCulture="true" culture="auto:en-us" uiCulture="auto:en-us"/>
</system.web>
<configuration>
在這裏,我已經啓用基於客戶端的區域性和設置文化和的UICulture爲「自動」與「EN-US」默認。
創建單獨的附屬程序集:
的MSDN Creating Satellite Assemblies文章也將有所幫助。 如果您是新來的衛星組件,請確保您閱讀Packaging and Deploying Resources。
在過去創建附屬程序集時,我發現使用VS構建事件很有用。這些是我會採取的步驟。
- 創建我的解決方案的獨立
Class Library
項目。
- 創建或添加我的
.resx
文件到此項目。
- 添加一個
Post-Build Event
到Project Properties
對話框。 (類似下面)
樣品VS生成後腳本:
set RESGEN="C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\resgen.exe"
set LINKER="C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\al.exe"
set ASSEMBLY=$(TargetName)
set SOURCEDIR=$(ProjectDir)
Set OUTDIR=$(TargetDir)
REM Build Default Culture Resources (en)
%RESGEN% %SOURCEDIR%en\%ASSEMBLY%.en.resx %SOURCEDIR%en\%ASSEMBLY%.resources
REM Embed Default Culture
%LINKER% /t:lib /embed:%SOURCEDIR%en\%ASSEMBLY%.resources /culture:en /out:%OUTDIR%%ASSEMBLY%.resources.dll
REM Embed English Culture
IF NOT EXIST %OUTDIR%en\ MKDIR $%OUTDIR%en\
%LINKER% /t:lib /embed:%SOURCEDIR%en\%ASSEMBLY%.resources /culture:en /out:%OUTDIR%en\%ASSEMBLY%.resources.dll
REM These are just a byproduct of using the project build event to run the resource build script
IF EXIST %OUTDIR%%ASSEMBLY%.dll DEL %OUTDIR%%ASSEMBLY%.dll
IF EXIST %OUTDIR%%ASSEMBLY%.pdb DEL %OUTDIR%%ASSEMBLY%.pdb
如果你不希望使用ResGen.exe轉換您.resx
文件,你可以做這樣的事情。
using System;
using System.Collections;
using System.IO;
using System.Resources;
namespace ResXConverter
{
public class ResxToResource
{
public void Convert(string resxPath, string resourcePath)
{
using (ResXResourceReader resxReader = new ResXResourceReader(resxPath))
using (IResourceWriter resWriter = new ResourceWriter(
new FileStream(resourcePath, FileMode.Create, FileAccess.Write)))
{
foreach (DictionaryEntry entry in resxReader)
{
resWriter.AddResource(entry.Key.ToString(), entry.Value);
}
resWriter.Generate();
resWriter.Close();
}
}
}
}
一個潛在的抽獎背上來執行轉換這種方式是引用System.Windows.Forms.dll
的需要。您仍然需要使用Assembly Linker。
編輯:由於wRAR提醒我們您是否在簽署裝配您的鑰匙must match。
我知道這一點,但我不想更改所有屬性。 – wRAR 2010-04-05 08:49:21