C# AppDomain.ResourceResolve事件
微软Visual Studio,C# 我需要将所有本地化的资源文件定位到。\resource子目录中。我无法使用配置文件的探测XML元素,也就是说,我真正的项目是dll(它将加载到外部应用程序中,而不位于托管应用程序目录中)。我尝试使用AppDomain.ResourceResolve事件,但遇到问题 现在我写了“Hello World”来展示它:C# AppDomain.ResourceResolve事件,c#,.net,visual-studio,resources,C#,.net,Visual Studio,Resources,微软Visual Studio,C# 我需要将所有本地化的资源文件定位到。\resource子目录中。我无法使用配置文件的探测XML元素,也就是说,我真正的项目是dll(它将加载到外部应用程序中,而不位于托管应用程序目录中)。我尝试使用AppDomain.ResourceResolve事件,但遇到问题 现在我写了“Hello World”来展示它: using System; using System.Collections.Generic; using System.Globalization
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”项目也随附:。尝试使用其他构造函数:
ResourceManager res = new ResourceManager("Program", typeof(Program).Assembly);
如果我在
AppDomain.AssemblyResolve
而不是AppDomain.ResourceResolve
上注册我的事件处理程序,它会成功运行,但在这种情况下,AppDomain.AssemblyResolve
会生成两次(我不知道为什么)。此决定由@Josser发现-谢谢。所以问题解决了。如果有人知道为什么AppDomain.resourcesolve
在我的情况下不起作用,以及为什么AppDomain.AssemblyResolve
生成两次,我将非常感谢您的解释 不使用String.Format()的返回值当然是一个错误。我认为(我也有希望)我的代码中有一个错误。一点解释可能会有很大帮助。响应晚,但可能有用。从.NET Framework 4开始,所有程序集(包括资源程序集)都会引发System.ResolveEventHandler事件。在早期版本中,资源程序集不会引发该事件。如果操作系统已本地化,则可能会多次调用该处理程序:回退链中的每个区域性调用一次[