代码之家  ›  专栏  ›  技术社区  ›  Carra

异常信息的英文版本?

  •  268
  • Carra  · 技术社区  · 16 年前

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

    15 回复  |  直到 9 年前
        1
  •  75
  •   Community CDub    8 年前

    这个问题可以部分解决。框架异常代码根据当前线程区域设置从其资源加载错误消息。在某些异常情况下,这会在访问消息属性时发生。

    对于这些异常,您可以通过在日志记录时将线程区域设置短暂切换为en US(预先保存原始用户区域设置,然后立即恢复),获得消息的完整美英版本。

    在单独的线程上这样做更好:这样可以确保不会有任何副作用。例如:

    try
    {
      System.IO.StreamReader sr=new System.IO.StreamReader(@"c:\does-not-exist");
    }
    catch(Exception ex)
    {
      Console.WriteLine(ex.ToString()); //Will display localized message
      ExceptionLogger el = new ExceptionLogger(ex);
      System.Threading.Thread t = new System.Threading.Thread(el.DoLog);
      t.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
      t.Start();
    }
    

    class ExceptionLogger
    {
      Exception _ex;
    
      public ExceptionLogger(Exception ex)
      {
        _ex = ex;
      }
    
      public void DoLog()
      {
        Console.WriteLine(_ex.ToString()); //Will display en-US message
      }
    }
    

    但是, Joe 正确地指出,在此回复的早期版本的评论中,在引发异常时,一些消息已经(部分)从语言资源加载。

    除了使用不切实际的黑客,比如在一个线程上运行所有非UI代码,首先使用en-US语言环境,您似乎对此无能为力:.NET Framework异常代码没有覆盖错误消息语言环境的工具。

        2
  •  71
  •   user461128    14 年前

    您可以在以下位置搜索原始异常消息: unlocalize.com

        3
  •  44
  •   MPelletier    9 年前

    也许这是一个有争议的观点,但不是将文化设定为 en-US ,您可以将其设置为 Invariant . 在 不变的 文化,错误消息是英文的。

    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
    Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
    

    它的优点是看起来没有偏见,特别是对于非美国英语国家。(又称a.k.a.避免同事的冷嘲热讽)

        4
  •  14
  •   Simon Mourier    6 年前

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

    <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 fr )添加到…不存在的程序集(任意版本999)。

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

    当然,我不认为这是由微软支持,所以使用在您自己的风险。好的,如果你检测到一个问题,你可以删除这个配置并检查它是否无关。

        5
  •  10
  •   gliderkite    13 年前

    Windows需要安装要使用的UI语言。它没有,它无法神奇地知道翻译的信息是什么。

    在安装了pt的en US windows 7 ultimate中,以下代码:

    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("pt-PT");
    string msg1 = new DirectoryNotFoundException().Message;
    
    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
    string msg2 = new FileNotFoundException().Message;
    
    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr-FR");
    string msg3 = new FileNotFoundException().Message;
    

    生成pt、en US和en US格式的消息。由于没有安装法语区域性文件,因此默认为windows默认(已安装?)语言。

        6
  •  5
  •   Barbarian    13 年前

    我知道这是一个老话题,但我认为我的解决方案可能与任何在网络搜索中偶然发现它的人都非常相关:

    在异常记录器中,您可以记录ex.GetType.ToString,这将保存异常类的名称。我希望类的名称应该独立于语言,因此总是用英语表示(例如“System.FileNotFoundException”),尽管目前我没有访问外语系统来测试这个想法。

    如果你真的想要错误消息文本,你可以用你喜欢的语言创建一个包含所有可能的异常类名及其等价消息的字典,但是对于英语,我认为类名已经足够了。

        7
  •  4
  •   Fabio Mastelari Fabio Mastelari    16 年前
    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:)

        8
  •  4
  •   Piotr Niewinski    5 年前

    背景 Thread.CurrentThread.CurrentUICulture 将用于本地化异常。如果您需要两种类型的异常(一种为用户,一种为您),您可以使用以下函数来翻译异常消息。它在.NET库资源中搜索原始文本,以获取资源键,然后返回翻译后的值。但是有一个缺点我还没有找到一个好的解决方案:在资源中包含{0}的消息将找不到。如果有人有好的解决办法,我将不胜感激。

    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)
    }
    
        9
  •  3
  •   Daniel Rose    11 年前

    .NET framework分为两部分:

    1. NET框架本身
    2. .NETFramework语言包

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

    根据您的具体情况,一个解决方案是卸载语言包(即告诉客户端这样做)。在这种情况下,例外文本将使用英语。但是请注意,框架提供的所有其他文本也将是英文的(例如消息框上的按钮标签、应用程序命令的键盘快捷键)。

        10
  •  2
  •   jan    6 年前

    基于Undercover1989答案,但考虑参数以及消息由多个资源字符串组成时(如参数异常)。

    public static string TranslateExceptionMessage(Exception exception, CultureInfo targetCulture)
    {
        Assembly a = exception.GetType().Assembly;
        ResourceManager rm = new ResourceManager(a.GetName().Name, a);
        ResourceSet rsOriginal = rm.GetResourceSet(Thread.CurrentThread.CurrentUICulture, true, true);
        ResourceSet rsTranslated = rm.GetResourceSet(targetCulture, true, true);
    
        var result = exception.Message;
    
        foreach (DictionaryEntry item in rsOriginal)
        {
            if (!(item.Value is string message))
                continue;
    
            string translated = rsTranslated.GetString(item.Key.ToString(), false);
    
            if (!message.Contains("{"))
            {
                result = result.Replace(message, translated);
            }
            else
            {
                var pattern = $"{Regex.Escape(message)}";
                pattern = Regex.Replace(pattern, @"\\{([0-9]+)\}", "(?<group$1>.*)");
    
                var regex = new Regex(pattern);
    
                var replacePattern = translated;
                replacePattern = Regex.Replace(replacePattern, @"{([0-9]+)}", @"${group$1}");
                replacePattern = replacePattern.Replace("\\$", "$");
    
                result = regex.Replace(result, replacePattern);
            }
        }
    
        return result;
    }
    
        11
  •  1
  •   Wai Ha Lee captain-yossarian from Ukraine    5 年前

    我可以想象其中一种方法:

    1. 例外情况仅由您读取,即它们不是客户端功能,因此您可以使用硬连线的非本地化字符串,在土耳其模式下运行时不会更改。

    2. 包括错误代码,例如。 0x00000001 每一个错误,以便您可以轻松地在英文表格中查找。

        12
  •  1
  •   Wai Ha Lee captain-yossarian from Ukraine    5 年前

    我也遇到过同样的情况,我在这里和其他地方找到的所有答案都没有帮助或不令人满意:

    这个 Thread.CurrentUICulture 更改.net异常的语言,但不适用于 Win32Exception ,它使用Windows UI本身语言中的Windows资源。所以我从来没有打印过 用英语而不是德语,甚至不用 FormatMessage() 如中所述
    How to get Win32Exception in English?

    此类的静态函数可以在不同语言的Windows安装上执行: CreateMessages()
    SaveMessagesToXML() 在创建或加载语言时,将它们保存到尽可能多的XML文件中
    LoadMessagesFromXML()


    已使用VS2008进行测试,可随时使用。欢迎提出意见和建议!

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Globalization;
    using System.Reflection;
    using System.Threading;
    using System.Xml;
    
    public struct CException
    {
      //----------------------------------------------------------------------------
      public CException(Exception i_oException)
      {
        m_oException = i_oException;
        m_oCultureInfo = null;
        m_sMessage = null;
      }
    
      //----------------------------------------------------------------------------
      public CException(Exception i_oException, string i_sCulture)
      {
        m_oException = i_oException;
        try
        { m_oCultureInfo = new CultureInfo(i_sCulture); }
        catch
        { m_oCultureInfo = CultureInfo.InvariantCulture; }
        m_sMessage = null;
      }
    
      //----------------------------------------------------------------------------
      public CException(Exception i_oException, CultureInfo i_oCultureInfo)
      {
        m_oException = i_oException;
        m_oCultureInfo = i_oCultureInfo == null ? CultureInfo.InvariantCulture : i_oCultureInfo;
        m_sMessage = null;
      }
    
      //----------------------------------------------------------------------------
      // GetMessage
      //----------------------------------------------------------------------------
      public string GetMessage() { return GetMessage(m_oException, m_oCultureInfo); }
    
      public string GetMessage(String i_sCulture) { return GetMessage(m_oException, i_sCulture); }
    
      public string GetMessage(CultureInfo i_oCultureInfo) { return GetMessage(m_oException, i_oCultureInfo); }
    
      public static string GetMessage(Exception i_oException) { return GetMessage(i_oException, CultureInfo.InvariantCulture); }
    
      public static string GetMessage(Exception i_oException, string i_sCulture)
      {
        CultureInfo oCultureInfo = null;
        try
        { oCultureInfo = new CultureInfo(i_sCulture); }
        catch
        { oCultureInfo = CultureInfo.InvariantCulture; }
        return GetMessage(i_oException, oCultureInfo);
      }
    
      public static string GetMessage(Exception i_oException, CultureInfo i_oCultureInfo)
      {
        if (i_oException == null) return null;
        if (i_oCultureInfo == null) i_oCultureInfo = CultureInfo.InvariantCulture;
    
        if (ms_dictCultureExceptionMessages == null) return null;
        if (!ms_dictCultureExceptionMessages.ContainsKey(i_oCultureInfo))
          return CreateMessage(i_oException, i_oCultureInfo);
    
        Dictionary<string, string> dictExceptionMessage = ms_dictCultureExceptionMessages[i_oCultureInfo];
        string sExceptionName = i_oException.GetType().FullName;
        sExceptionName = MakeXMLCompliant(sExceptionName);
        Win32Exception oWin32Exception = (Win32Exception)i_oException;
        if (oWin32Exception != null)
          sExceptionName += "_" + oWin32Exception.NativeErrorCode;
        if (dictExceptionMessage.ContainsKey(sExceptionName))
          return dictExceptionMessage[sExceptionName];
        else
          return CreateMessage(i_oException, i_oCultureInfo);
      }
    
      //----------------------------------------------------------------------------
      // CreateMessages
      //----------------------------------------------------------------------------
      public static void CreateMessages(CultureInfo i_oCultureInfo)
      {
        Thread oTH = new Thread(new ThreadStart(CreateMessagesInThread));
        if (i_oCultureInfo != null)
        {
          oTH.CurrentCulture = i_oCultureInfo;
          oTH.CurrentUICulture = i_oCultureInfo;
        }
        oTH.Start();
        while (oTH.IsAlive)
        { Thread.Sleep(10); }
      }
    
      //----------------------------------------------------------------------------
      // LoadMessagesFromXML
      //----------------------------------------------------------------------------
      public static void LoadMessagesFromXML(string i_sPath, string i_sBaseFilename)
      {
        if (i_sBaseFilename == null) i_sBaseFilename = msc_sBaseFilename;
    
        string[] asFiles = null;
        try
        {
          asFiles = System.IO.Directory.GetFiles(i_sPath, i_sBaseFilename + "_*.xml");
        }
        catch { return; }
    
        ms_dictCultureExceptionMessages.Clear();
        for (int ixFile = 0; ixFile < asFiles.Length; ixFile++)
        {
          string sXmlPathFilename = asFiles[ixFile];
    
          XmlDocument xmldoc = new XmlDocument();
          try
          {
            xmldoc.Load(sXmlPathFilename);
            XmlNode xmlnodeRoot = xmldoc.SelectSingleNode("/" + msc_sXmlGroup_Root);
    
            string sCulture = xmlnodeRoot.SelectSingleNode(msc_sXmlGroup_Info + "/" + msc_sXmlData_Culture).Value;
            CultureInfo oCultureInfo = new CultureInfo(sCulture);
    
            XmlNode xmlnodeMessages = xmlnodeRoot.SelectSingleNode(msc_sXmlGroup_Messages);
            XmlNodeList xmlnodelistMessage = xmlnodeMessages.ChildNodes;
            Dictionary<string, string> dictExceptionMessage = new Dictionary<string, string>(xmlnodelistMessage.Count + 10);
            for (int ixNode = 0; ixNode < xmlnodelistMessage.Count; ixNode++)
              dictExceptionMessage.Add(xmlnodelistMessage[ixNode].Name, xmlnodelistMessage[ixNode].InnerText);
            ms_dictCultureExceptionMessages.Add(oCultureInfo, dictExceptionMessage);
          }
          catch
          { return; }
        }
      }
    
      //----------------------------------------------------------------------------
      // SaveMessagesToXML
      //----------------------------------------------------------------------------
      public static void SaveMessagesToXML(string i_sPath, string i_sBaseFilename)
      {
        if (i_sBaseFilename == null) i_sBaseFilename = msc_sBaseFilename;
    
        foreach (KeyValuePair<CultureInfo, Dictionary<string, string>> kvpCultureExceptionMessages in ms_dictCultureExceptionMessages)
        {
          string sXmlPathFilename = i_sPath + i_sBaseFilename + "_" + kvpCultureExceptionMessages.Key.TwoLetterISOLanguageName + ".xml";
          Dictionary<string, string> dictExceptionMessage = kvpCultureExceptionMessages.Value;
    
          XmlDocument xmldoc = new XmlDocument();
          XmlWriter xmlwriter = null;
          XmlWriterSettings writerSettings = new XmlWriterSettings();
          writerSettings.Indent = true;
    
          try
          {
            XmlNode xmlnodeRoot = xmldoc.CreateElement(msc_sXmlGroup_Root);
            xmldoc.AppendChild(xmlnodeRoot);
            XmlNode xmlnodeInfo = xmldoc.CreateElement(msc_sXmlGroup_Info);
            XmlNode xmlnodeMessages = xmldoc.CreateElement(msc_sXmlGroup_Messages);
            xmlnodeRoot.AppendChild(xmlnodeInfo);
            xmlnodeRoot.AppendChild(xmlnodeMessages);
    
            XmlNode xmlnodeCulture = xmldoc.CreateElement(msc_sXmlData_Culture);
            xmlnodeCulture.InnerText = kvpCultureExceptionMessages.Key.Name;
            xmlnodeInfo.AppendChild(xmlnodeCulture);
    
            foreach (KeyValuePair<string, string> kvpExceptionMessage in dictExceptionMessage)
            {
              XmlNode xmlnodeMsg = xmldoc.CreateElement(kvpExceptionMessage.Key);
              xmlnodeMsg.InnerText = kvpExceptionMessage.Value;
              xmlnodeMessages.AppendChild(xmlnodeMsg);
            }
    
            xmlwriter = XmlWriter.Create(sXmlPathFilename, writerSettings);
            xmldoc.WriteTo(xmlwriter);
          }
          catch (Exception e)
          { return; }
          finally
          { if (xmlwriter != null) xmlwriter.Close(); }
        }
      }
    
      //----------------------------------------------------------------------------
      // CreateMessagesInThread
      //----------------------------------------------------------------------------
      private static void CreateMessagesInThread()
      {
        Thread.CurrentThread.Name = "CException.CreateMessagesInThread";
    
        Dictionary<string, string> dictExceptionMessage = new Dictionary<string, string>(0x1000);
    
        GetExceptionMessages(dictExceptionMessage);
        GetExceptionMessagesWin32(dictExceptionMessage);
    
        ms_dictCultureExceptionMessages.Add(Thread.CurrentThread.CurrentUICulture, dictExceptionMessage);
      }
    
      //----------------------------------------------------------------------------
      // GetExceptionTypes
      //----------------------------------------------------------------------------
      private static List<Type> GetExceptionTypes()
      {
        Assembly[] aoAssembly = AppDomain.CurrentDomain.GetAssemblies();
    
        List<Type> listoExceptionType = new List<Type>();
    
        Type oExceptionType = typeof(Exception);
        for (int ixAssm = 0; ixAssm < aoAssembly.Length; ixAssm++)
        {
          if (!aoAssembly[ixAssm].GlobalAssemblyCache) continue;
          Type[] aoType = aoAssembly[ixAssm].GetTypes();
          for (int ixType = 0; ixType < aoType.Length; ixType++)
          {
            if (aoType[ixType].IsSubclassOf(oExceptionType))
              listoExceptionType.Add(aoType[ixType]);
          }
        }
    
        return listoExceptionType;
      }
    
      //----------------------------------------------------------------------------
      // GetExceptionMessages
      //----------------------------------------------------------------------------
      private static void GetExceptionMessages(Dictionary<string, string> i_dictExceptionMessage)
      {
        List<Type> listoExceptionType = GetExceptionTypes();
        for (int ixException = 0; ixException < listoExceptionType.Count; ixException++)
        {
          Type oExceptionType = listoExceptionType[ixException];
          string sExceptionName = MakeXMLCompliant(oExceptionType.FullName);
          try
          {
            if (i_dictExceptionMessage.ContainsKey(sExceptionName))
              continue;
            Exception e = (Exception)(Activator.CreateInstance(oExceptionType));
            i_dictExceptionMessage.Add(sExceptionName, e.Message);
          }
          catch (Exception)
          { i_dictExceptionMessage.Add(sExceptionName, null); }
        }
      }
    
      //----------------------------------------------------------------------------
      // GetExceptionMessagesWin32
      //----------------------------------------------------------------------------
      private static void GetExceptionMessagesWin32(Dictionary<string, string> i_dictExceptionMessage)
      {
        string sTypeName = MakeXMLCompliant(typeof(Win32Exception).FullName) + "_";
        for (int iError = 0; iError < 0x4000; iError++)  // Win32 errors may range from 0 to 0xFFFF
        {
          Exception e = new Win32Exception(iError);
          if (!e.Message.StartsWith("Unknown error (", StringComparison.OrdinalIgnoreCase))
            i_dictExceptionMessage.Add(sTypeName + iError, e.Message);
        }
      }
    
      //----------------------------------------------------------------------------
      // CreateMessage
      //----------------------------------------------------------------------------
      private static string CreateMessage(Exception i_oException, CultureInfo i_oCultureInfo)
      {
        CException oEx = new CException(i_oException, i_oCultureInfo);
        Thread oTH = new Thread(new ParameterizedThreadStart(CreateMessageInThread));
        oTH.Start(oEx);
        while (oTH.IsAlive)
        { Thread.Sleep(10); }
        return oEx.m_sMessage;
      }
    
      //----------------------------------------------------------------------------
      // CreateMessageInThread
      //----------------------------------------------------------------------------
      private static void CreateMessageInThread(Object i_oData)
      {
        if (i_oData == null) return;
        CException oEx = (CException)i_oData;
        if (oEx.m_oException == null) return;
    
        Thread.CurrentThread.CurrentUICulture = oEx.m_oCultureInfo == null ? CultureInfo.InvariantCulture : oEx.m_oCultureInfo;
        // create new exception in desired culture
        Exception e = null;
        Win32Exception oWin32Exception = (Win32Exception)(oEx.m_oException);
        if (oWin32Exception != null)
          e = new Win32Exception(oWin32Exception.NativeErrorCode);
        else
        {
          try
          {
            e = (Exception)(Activator.CreateInstance(oEx.m_oException.GetType()));
          }
          catch { }
        }
        if (e != null)
          oEx.m_sMessage = e.Message;
      }
    
      //----------------------------------------------------------------------------
      // MakeXMLCompliant
      // from https://www.w3.org/TR/xml/
      //----------------------------------------------------------------------------
      private static string MakeXMLCompliant(string i_sName)
      {
        if (string.IsNullOrEmpty(i_sName))
          return "_";
    
        System.Text.StringBuilder oSB = new System.Text.StringBuilder();
        for (int ixChar = 0; ixChar < (i_sName == null ? 0 : i_sName.Length); ixChar++)
        {
          char character = i_sName[ixChar];
          if (IsXmlNodeNameCharacterValid(ixChar, character))
            oSB.Append(character);
        }
        if (oSB.Length <= 0)
          oSB.Append("_");
        return oSB.ToString();
      }
    
      //----------------------------------------------------------------------------
      private static bool IsXmlNodeNameCharacterValid(int i_ixPos, char i_character)
      {
        if (i_character == ':') return true;
        if (i_character == '_') return true;
        if (i_character >= 'A' && i_character <= 'Z') return true;
        if (i_character >= 'a' && i_character <= 'z') return true;
        if (i_character >= 0x00C0 && i_character <= 0x00D6) return true;
        if (i_character >= 0x00D8 && i_character <= 0x00F6) return true;
        if (i_character >= 0x00F8 && i_character <= 0x02FF) return true;
        if (i_character >= 0x0370 && i_character <= 0x037D) return true;
        if (i_character >= 0x037F && i_character <= 0x1FFF) return true;
        if (i_character >= 0x200C && i_character <= 0x200D) return true;
        if (i_character >= 0x2070 && i_character <= 0x218F) return true;
        if (i_character >= 0x2C00 && i_character <= 0x2FEF) return true;
        if (i_character >= 0x3001 && i_character <= 0xD7FF) return true;
        if (i_character >= 0xF900 && i_character <= 0xFDCF) return true;
        if (i_character >= 0xFDF0 && i_character <= 0xFFFD) return true;
        // if (i_character >= 0x10000 && i_character <= 0xEFFFF) return true;
    
        if (i_ixPos > 0)
        {
          if (i_character == '-') return true;
          if (i_character == '.') return true;
          if (i_character >= '0' && i_character <= '9') return true;
          if (i_character == 0xB7) return true;
          if (i_character >= 0x0300 && i_character <= 0x036F) return true;
          if (i_character >= 0x203F && i_character <= 0x2040) return true;
        }
        return false;
      }
    
      private static string msc_sBaseFilename = "exception_messages";
      private static string msc_sXmlGroup_Root = "exception_messages";
      private static string msc_sXmlGroup_Info = "info";
      private static string msc_sXmlGroup_Messages = "messages";
      private static string msc_sXmlData_Culture = "culture";
    
      private Exception m_oException;
      private CultureInfo m_oCultureInfo;
      private string m_sMessage;
    
      static Dictionary<CultureInfo, Dictionary<string, string>> ms_dictCultureExceptionMessages = new Dictionary<CultureInfo, Dictionary<string, string>>();
    }
    
    internal class Program
    {
      public static void Main()
      {
        CException.CreateMessages(null);
        CException.SaveMessagesToXML(@"d:\temp\", "emsg");
        CException.LoadMessagesFromXML(@"d:\temp\", "emsg");
      }
    }
    
        13
  •  -1
  •   Branko Dimitrijevic    15 年前

    您应该记录调用堆栈,而不仅仅是错误消息(IIRC,simple exception.ToString()应该为您这样做)。从这里,您可以确定异常的确切来源,并且通常可以推断它是哪个异常。

        14
  •  -1
  •   user3472484    11 年前

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

        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();
            }
    
        15
  •  -1
  •   Ron16    8 年前

    为此,以下代码

    1. 更改当前的UIC区域性
    2. 使用“GetType()”重新创建引发的异常对象(&“Activator.CreateInstance(t)”
    3. 在新UICuture中显示新异常对象的消息
    4.     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();
      
           }
      
        16
  •  -2
  •   Wai Ha Lee captain-yossarian from Ukraine    5 年前

    英文例外讯息

    try
    {
        ......
    }
    catch (Exception ex)
    {
          throw new UserFriendlyException(L("ExceptionmessagesinEnglish"));
    }
    

    <text name="ExceptionmessagesinEnglish">Exception Message in English</text>