[英]AppDomain.ResourceResolve event
MS Visual Studio,C#。
我需要將所有本地化的資源文件定位到。\\ resource子目錄中。 我不能使用config-file的XML探測元素,即我真正的項目是dll(它將加載到外部應用程序中,而不位於托管應用程序目錄中)。 我嘗試使用AppDomain.ResourceResolve事件,但是出現問題...
現在我寫了《 Hello World》來展示它:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading;
namespace HelloWorld {
class Program {
static void Main(string[] args) {
AppDomain domain = AppDomain.CurrentDomain;
Thread thread = Thread.CurrentThread;
thread.CurrentUICulture = new CultureInfo("en");
domain.ResourceResolve += domain_ResourceResolve;
ResourceManager res = new ResourceManager(typeof(Program));
Console.WriteLine(res.GetString("Message"));
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
res.ReleaseAllResources();
}
static System.Reflection.Assembly domain_ResourceResolve(object sender,
ResolveEventArgs args) {
Assembly assembly = typeof(Program).Assembly;
String name = Path.Combine(Path.GetDirectoryName(assembly.Location),
String.Format("resources\\en\\{0}.resources.dll", Path.GetFileNameWithoutExtension(
assembly.Location)));
if (!File.Exists(name)) {
Console.WriteLine("'{0}' file not found.", name);
return null;
}
else {
Assembly result = Assembly.LoadFrom(name);
if (result != null)
Console.WriteLine("'{0}' loaded.", name);
return result;
}
}
}
}
Program.resx不存在,即,如果存在,則不會發生ResourceResolve事件。 也存在Program.en.resx和Program.ru.resx文件。 在項目的屬性中,設置后構建事件:
rmdir .\resources /S /Q
mkdir .\resources
move .\en .\resources\en
move .\ru .\resources\ru
找到並成功加載了我的本地化資源,但出現異常(查看屏幕)...
我隨附的“ Hello World”項目還包括: 資料來源 。
如果我在AppDomain.AssemblyResolve
而不是AppDomain.ResourceResolve
上注冊事件處理程序,則它可以成功運行 ,但在這種情況下AppDomain.AssemblyResolve
生成兩次 (我不知道為什么)。 該決定由@Josser找到-謝謝。 這樣問題就解決了。 如果有人知道為什么AppDomain.ResourceResolve
在我的情況下不起作用,以及AppDomain.AssemblyResolve
為什么生成兩次 ,我將不勝感激。
嘗試使用其他構造函數:
ResourceManager res = new ResourceManager("Program", typeof(Program).Assembly);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.