【问题标题】:How do I look up the proper Windows System Error Code to use in my application?如何查找正确的 Windows 系统错误代码以在我的应用程序中使用?
【发布时间】:2011-04-18 22:37:17
【问题描述】:

我正在编写一个 C# .NET 2.0 应用程序,其中当预期通过SerialPort 接收消息时。如果没有接收到帧(即超时)或被确定为无效,我需要使用SetLastError 设置错误代码。 Windows 有大量的错误代码。是否有简单的工具或参考来帮助缩小要使用的正确错误代码?

附加信息

虽然我的偏好是抛出异常并在堆栈更高的位置处理它,但在这种情况下这不是一个选项,因为我正在更新的应用程序并非旨在利用这种有用的功能。

【问题讨论】:

  • 为什么要打电话给SetLastError
  • @SLaks:我想使用SetLastError,因为上面有一个将错误记录到文本文件的功能,我想这总比没有好。

标签: c# windows error-code


【解决方案1】:

不幸的是,上面的方法对我不起作用,但这对我来说非常有效,粘贴整个代码以便可以直接在 C# 中复制粘贴

public static class WinErrors
{
    /// <summary>
    /// Gets a user friendly string message for a system error code
    /// </summary>
    /// <param name="errorCode">System error code</param>
    /// <returns>Error string</returns>
    public static string GetSystemMessage(uint errorCode)
    {
        var exception = new Win32Exception((int)errorCode);
        return exception.Message;
    }
}

【讨论】:

    【解决方案2】:
    using System.Runtime.InteropServices;       // DllImport
    
    public static string GetSystemMessage(int errorCode) {
    int capacity = 512;
    int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
    StringBuilder sb = new StringBuilder(capacity);
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, IntPtr.Zero, errorCode, 0,
        sb, sb.Capacity, IntPtr.Zero);
    int i = sb.Length;
    if (i>0 && sb[i - 1] == 10) i--;
    if (i>0 && sb[i - 1] == 13) i--;
    sb.Length = i;
    return sb.ToString();
    }
    
    [DllImport("kernel32.dll")]
    public static extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId,
        int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr Arguments);
    

    【讨论】:

      【解决方案3】:

      在“过去的美好时光”(C 和 C++)中,可能的 Windows 错误列表在 winerror.h 中定义

      更新:以下链接已失效。不确定该文件是否仍可供下载,但所有Windows System Error Code definitions 都可以在此链接中找到。

      这个文件可以在Microsoft's site 上找到(尽管它的历史可以追溯到 2003 年,这让我有点惊讶 - 可能值得寻找更新的版本)。

      但如果您正在获取(或想要设置)Win32 错误代码,则可以在此处找到定义。

      【讨论】:

      【解决方案4】:

      你可以在这里找到它们的列表:

      http://en.kioskea.net/faq/2347-error-codes-in-windows

      然后只需搜索“Serial”并使用最适合您错误的那个

      【讨论】:

      猜你喜欢
      • 2019-03-07
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 2021-07-10
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多