我们通过编写Exception来记录系统中发生的任何异常。消息发送到文件。但是,它们是在客户端的文化中编写的。土耳其语的错误对我来说意义不大。
那么,我们如何在不改变用户文化的情况下用英语记录错误消息呢?
我们通过编写Exception来记录系统中发生的任何异常。消息发送到文件。但是,它们是在客户端的文化中编写的。土耳其语的错误对我来说意义不大。
那么,我们如何在不改变用户文化的情况下用英语记录错误消息呢?
当前回答
这可能是一个有争议的观点,但是与其将区域性设置为en-US,不如将其设置为Invariant。在“不变区域性”中,错误消息是英文的。
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
它的优点是看起来没有偏见,特别是对于非美式英语地区。(也就是避免同事的冷嘲热讽)
其他回答
英文异常消息
try
{
......
}
catch (Exception ex)
{
throw new UserFriendlyException(L("ExceptionmessagesinEnglish"));
}
然后进入本地化文件夹,把它放在projectName.xml中,然后添加
<text name="ExceptionmessagesinEnglish">Exception Message in English</text>
您应该记录调用堆栈,而不仅仅是错误消息(IIRC,简单的异常。tostring()应该为您做这件事)。从那里,您可以确定异常的确切来源,并且通常可以推断出它是哪个异常。
CultureInfo oldCI = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture ("en-US");
Thread.CurrentThread.CurrentUICulture=new CultureInfo("en-US");
try
{
System.IO.StreamReader sr=new System.IO.StreamReader(@"c:\does-not-exist");
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
Thread.CurrentThread.CurrentCulture = oldCI;
Thread.CurrentThread.CurrentUICulture = oldCI;
没有解决方法。
Tks:)
Setting Thread.CurrentThread.CurrentUICulture will be used to localize the exceptions. If you need two kinds of exceptions (one for the user, one for you) you can use the following function to translate the exception-message. It's searching in the .NET-Libraries resources for the original text to get the resource-key and then return the translated value. But there's one weakness I didn't find a good solution yet: Messages, that contains {0} in resources will not be found. If anyone has a good solution I would be grateful.
public static string TranslateExceptionMessage(Exception ex, CultureInfo targetCulture)
{
try
{
Assembly assembly = ex.GetType().Assembly;
ResourceManager resourceManager = new ResourceManager(assembly.GetName().Name, assembly);
ResourceSet originalResources = resourceManager.GetResourceSet(Thread.CurrentThread.CurrentUICulture, createIfNotExists: true, tryParents: true);
ResourceSet targetResources = resourceManager.GetResourceSet(targetCulture, createIfNotExists: true, tryParents: true);
foreach (DictionaryEntry originalResource in originalResources)
if (originalResource.Value.ToString().Equals(ex.Message.ToString(), StringComparison.Ordinal))
return targetResources.GetString(originalResource.Key.ToString(), ignoreCase: false); // success
}
catch { }
return ex.Message; // failed (error or cause it's not smart enough to find texts with '{0}'-patterns)
}
关于。net Core和以上,线程文档。CurrentUICulture推荐使用CultureInfo。属性检索和设置当前区域性。
CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
在一个相关的GitHub问题上,Tarek Mahmoud Sayed建议使用CultureInfo。defaultthreadcurrentuicculture以确保稍后创建的其他线程也将获得相同的区域性:
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
后者只在。net Framework 4.5(和。net Core 1.0)之后才可用。