我们通过编写Exception来记录系统中发生的任何异常。消息发送到文件。但是,它们是在客户端的文化中编写的。土耳其语的错误对我来说意义不大。

那么,我们如何在不改变用户文化的情况下用英语记录错误消息呢?


当前回答

您应该记录调用堆栈,而不仅仅是错误消息(IIRC,简单的异常。tostring()应该为您做这件事)。从那里,您可以确定异常的确切来源,并且通常可以推断出它是哪个异常。

其他回答

这里有一个解决方案,不需要任何编码,甚至适用于异常的文本加载过早,我们能够通过代码更改(例如,那些在mscorlib)。

它可能并不总是适用于每一种情况(这取决于你的设置,因为你需要能够创建一个。config文件之外的主。exe文件),但这对我来说是可行的。因此,只需在dev中创建一个app.config,(或[myapp].exe。Config或web。Config in production),包含以下行,例如:

<configuration>
  ...
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="mscorlib.resources" publicKeyToken="b77a5c561934e089"
                          culture="fr" /> <!-- change this to your language -->

        <bindingRedirect oldVersion="1.0.0.0-999.0.0.0" newVersion="999.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Xml.resources" publicKeyToken="b77a5c561934e089"
                          culture="fr" /> <!-- change this to your language -->

        <bindingRedirect oldVersion="1.0.0.0-999.0.0.0" newVersion="999.0.0.0"/>
      </dependentAssembly>

      <!-- add other assemblies and other languages here -->

    </assemblyBinding>
  </runtime>
  ...
</configuration>

它的作用是告诉框架将mscorlib的资源和System.Xml的资源的程序集绑定重定向到一个程序集,用于版本介于1到999之间的法语(文化设置为“fr”)。不存在(任意版本999)。

因此,当CLR为这两个程序集(mscorlib和System.xml)寻找法语资源时,它不会找到它们,而是优雅地回退到英语。根据上下文和测试,您可能希望将其他程序集添加到这些重定向(包含本地化资源的程序集)。

当然,我认为微软不支持这个功能,所以请自行承担使用风险。好吧,如果您发现了问题,您可以删除这个配置并检查它是否无关。

出于日志记录的目的,某些应用程序可能需要获取英文异常消息(除了在通常客户机的UICulture中显示它之外)。

为此,使用以下代码

changes the current UICulture recreates the thrown Exception object using "GetType()" & "Activator.CreateInstance(t)" displays the new Exception object's Message in the new UICuture and then finally changes the current UICulture back to earlier UICulture. try { int[] a = { 3, 6 }; Console.WriteLine(a[3]); //Throws index out of bounds exception System.IO.StreamReader sr = new System.IO.StreamReader(@"c:\does-not-exist"); // throws file not found exception throw new System.IO.IOException(); } catch (Exception ex) { Console.WriteLine(ex.Message); Type t = ex.GetType(); CultureInfo CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); object o = Activator.CreateInstance(t); System.Threading.Thread.CurrentThread.CurrentUICulture = CurrentUICulture; // Changing the UICulture back to earlier culture Console.WriteLine(((Exception)o).Message.ToString()); Console.ReadLine(); }

使用扩展方法覆盖捕获块中的异常消息,检查抛出的消息是否来自代码,如下所述。

    public static string GetEnglishMessageAndStackTrace(this Exception ex)
    {
        CultureInfo currentCulture = Thread.CurrentThread.CurrentUICulture;
        try
        {

            dynamic exceptionInstanceLocal = System.Activator.CreateInstance(ex.GetType());
            string str;
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

            if (ex.Message == exceptionInstanceLocal.Message)
            {
                dynamic exceptionInstanceENG = System.Activator.CreateInstance(ex.GetType());

                str = exceptionInstanceENG.ToString() + ex.StackTrace;

            }
            else
            {
                str = ex.ToString();
            }
            Thread.CurrentThread.CurrentUICulture = currentCulture;

            return str;

        }
        catch (Exception)
        {
            Thread.CurrentThread.CurrentUICulture = currentCulture;

            return ex.ToString();
        }

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框架分为两部分:

.NET框架本身 .NET框架语言包

在. net框架中,所有文本(例如异常消息、MessageBox上的按钮标签等)都是英文的。语言包具有本地化文本。

根据您的具体情况,解决方案是卸载语言包(即告诉客户端这样做)。在这种情况下,异常文本将是英文的。但是请注意,所有其他框架提供的文本也将是英文的(例如MessageBox上的按钮标签,ApplicationCommands的键盘快捷键)。