简体   繁体   English

C# - 当应用程序使用其他语言时,以英语获取异常消息?

[英]C# - Getting Exception messages in English when the application is in another language?

I am trying to localize my program but I would like error messages that are sent to the developers to appear in English. 我正在尝试本地化我的程序,但我希望发送给开发人员的错误消息以英文显示。 I haven't been able to find a way to make this happen since it seems that if the UI culture is set to another language when an error is thrown, it is thrown in that language. 我无法找到一种方法来实现这一点,因为似乎如果在抛出错误时将UI文化设置为另一种语言,则会抛出该语言。 Since I did not write this program myself, and it is quite large, I think it would be impractical to go create new try catch blocks to try and set the culture back to english whenever an error occurs or might possibly occur. 由于我自己并没有编写这个程序,并且它非常大,我认为创建新的try catch块以尝试在发生错误或可能发生错误时将文化设置回英语是不切实际的。 Currently the CurrentCulture and DefaultThreadCurrentCulture are always set to be English throughout the entire application, while the CurrentUICulture is set to the end user's language. 目前,CurrentCulture和DefaultThreadCurrentCulture在整个应用程序中始终设置为英语,而CurrentUICulture设置为最终用户的语言。

As I workaround, I currently have a function that has been iterating through a list of errors (using System.Resources.ResourceSets (which I assume are Windows errors, but I also need a way to find the .NET errors so I can iterate through those). It string replaces matching errors in other languages and replaces them with their English equivalents to build a large message of errors to be sent to the developers whenever the application crashes. Really, I don't have much to translate as most of the message is a server stack trace and showing where the exception was thrown. The biggest problem is translating the Inner Exception message and sometimes the main exception message since sometimes the errors thrown don't appear in the ResourceSet and sometimes use formatting items like '{0}'. 当我解决方法时,我目前有一个函数已经遍历一个错误列表(使用System.Resources.ResourceSets(我假设是Windows错误,但我还需要一种方法来查找.NET错误,以便我可以迭代它取代了其他语言中的匹配错误,并用它们的英语等价物替换它们,以便在应用程序崩溃时构建一个大的错误消息发送给开发人员。真的,我没有太多的翻译,因为大部分的message是一个服务器堆栈跟踪并显示抛出异常的位置。最大的问题是转换内部异常消息,有时是主异常消息,因为有时抛出的错误不会出现在ResourceSet中,有时会使用格式化项目,如'{0 }”。

Here is the code I have so far to translate the remaining errors. 这是我到目前为止翻译剩余错误的代码。 I'm still working on adding regex patterns to translate errors that use things like '{0}', so if anyone has suggestions for that or better ways to do this I'd appreciate suggestions. 我仍在努力添加正则表达式模式来翻译使用“{0}”之类的错误,所以如果有人对此提出建议或更好的方法,我会很感激建议。

    public static string TranslateExceptionMessageTest(string exmsg, Exception e, CultureInfo currentui)
    {
        CultureInfo test = Thread.CurrentThread.CurrentUICulture;
        string matchingstr = "";
        string newstr = exmsg;
        string resourcecollection = "";

        Assembly a = e.GetType().Assembly;
        ResourceManager rm = new ResourceManager(a.GetName().Name, a);
        ResourceSet rsOriginal = rm.GetResourceSet(currentui, true, true);
        ResourceSet rsTranslated = rm.GetResourceSet(new CultureInfo("en-US"), true, true);
        foreach (DictionaryEntry item in rsOriginal)
        {
            if (exmsg.Contains(item.Value.ToString()))
            {
                if (item.Key.ToString() == "Word_At") // sometimes with spanish errors this replaces words containing the letters 'en' with 'at'.
                {
                    string newat = "   " + item.Value.ToString() + " "; // this is the formatting the word 'at' appears with, in any culture I've tested.
                    matchingstr = "   " + rsTranslated.GetString(item.Key.ToString(), false) + " ";
                    newstr = newstr.Replace(newat, matchingstr);
                }
                else
                {
                    matchingstr = rsTranslated.GetString(item.Key.ToString(), false);
                    newstr = newstr.Replace(item.Value.ToString(), matchingstr);
                }
            }
            resourcecollection = resourcecollection + Environment.NewLine + "Key: " + item.Key.ToString() + Environment.NewLine + "Value: " + item.Value.ToString();
        }
        return newstr; // success
    }

I have also tried using the method posted here ( Exception messages in English? ) but without much luck. 我也试过使用这里发布的方法( 英文异常消息? )但没有太多运气。 I still ended up with the same localized error messages. 我仍然得到相同的本地化错误消息。 Here is the code where I know an error is being thrown but it doesn't seem like the catch block is doing anything to change the language. 这是我知道错误被抛出的代码,但似乎catch块没有做任何改变语言的事情。 My ExceptionLogger class is set up the same way as in the Stackoverflow example with the addition of a line to write the error to a file. 我的ExceptionLogger类的设置方式与Stackoverflow示例中的相同,只需添加一行即可将错误写入文件。 The error is being thrown at wcf.Client.Ping() (I don't care about the actual error. I'm using it to test). 错误是在wcf.Client.Ping()抛出(我不关心实际错误。我正在使用它来测试)。

 private void PreloadWcfDlls(object state)
 {
        if (Global.Inst.ServerMode == ApplicationServerMode.Unknown)
            return;

        try
        {
            using (var wcf = ClientGrabber.GetSchemaClient(Global.Inst.ServerMode))
            {
                wcf.Client.Ping();
            }
        }
        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();
        }
 }

If nothing else, is there a way I can get a list of all possible .NET Framework errors in English as well as in other languages? 如果没有别的,有没有办法可以用英语和其他语言获得所有可能的.NET Framework错误列表? Is there a class I can access to get these from within my program or a list elsewhere? 是否有一个我可以访问的课程从我的程序或其他地方的列表中获取这些? I've tried looking at sites like unlocalize.com and finderr.net but I really don't want to have to write something to crawl through all the pages to find every possible error. 我曾尝试查看像unlocalize.com和finderr.net这样的网站,但我真的不想写一些东西来抓取所有页面来查找每个可能的错误。

Sorry if I'm completely missing something. 对不起,如果我完全错过了什么。 I'm pretty new to C# and programming in general and this problem is driving me kind of crazy! 我对C#和编程很新,这个问题让我有点疯狂!

Edit: I forgot to add that I would prefer to avoid a solutions like these where you have to be constantly changing the CurrentUICulture: 编辑:我忘了补充一点,我宁愿避免这样的解决方案,你必须不断改变CurrentUICulture:

Force exceptions language in English 用英语强制例外语言

Prevent exception messages from being translated into the user's language? 防止异常消息被翻译成用户的语言?

Or solutions where you delete language packs or something on the user's computer or just set the errors to be in English when debugging (these error logs will also be sent from an end users computer in the case that the application crashes and if they are using another language we need the errors logged in English). 或者在用户计算机上删除语言包或其他内容的解决方案,或者在调试时将错误设置为英语(如果应用程序崩溃并且如果他们正在使用其他错误日志,则也会从最终用户计算机发送这些错误日志语言我们需要用英语记录的错误)。

Also, I know I could just google the error messages or use unlocalize.com or finderr.net to translate the messages but I think the other developers might kill me if they had to do that, hah. 此外,我知道我可以只是谷歌错误消息或使用unlocalize.com或finderr.net来翻译消息,但我认为其他开发人员可能会杀了我,如果他们必须这样做,哈。 I guess if worse comes to worst I could query the unlocalize site? 我想如果情况更糟,我可以查询unlocalize网站? Seems like a real pain though. 看起来真的很痛苦。

The exception framework loads the error messages based on culture of current thread. 异常框架根据当前线程的文化加载错误消息。 So what you can do is, catch the exception and in catch block you can make your own logger object and set its culture according to your need. 所以你可以做的是捕获异常,在catch块中你可以创建自己的logger对象并根据你的需要设置它的文化。

    try
{
//.....Code Goes Here
}
Catch (Exception ex)
{
   var eh = new ExceptionHandler("Your-Culture");
   //....code goes here
}

Public class ExceptionHandler
{
//code goes on
    public ExceptionHandler(string culture)
{
//set your culture here
}
}

Here you can find a solution for the problem. 在这里,您可以找到问题的解决方案。 To make the long story short: 长话短说:

 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(); } 

Where the ExceptionLogger class looks something like: ExceptionLogger类看起来像:

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

试试这个:

Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#中如何以指定语言(英文)显示MSSQL异常信息? - How to display MSSQL exception messages in a specified language (English) in C#? 在C#中将键盘语言从英语更改为其他语言时,如何以编程方式比较零 - How to compare number zero programmatically when the keyboard language is changed from english to other language in C# intellij rider c# 英文文档 - intellij rider c# documentation english language 异常被忽略(C#表单应用程序) - Exception getting ignored (C# Form application) 是否可以将Windows语言栏设置为英语或从ac#application返回默认值 - Is it possible to set the Windows language bar to english or back to the default from a c# application 英文异常信息? - Exception messages in English? C#表单应用程序获取ClipboardFormatListener仅在用户粘贴内容时接收消息 - C# Form Application Getting a ClipboardFormatListener to only receive messages when a user pastes content 当我从 URL 读取 PDF 时,它正确显示英文数据,但其他语言文本在 C# 中不正确 - When I read PDF from URL it shows English data correctly but other language text is not Properly in C# 在C#中获取另一个应用程序的界限? - Getting bounds of another application in C#? 自定义异常消息C# - Custom Exception Messages C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM