zoukankan      html  css  js  c++  java
  • .NET(C#):使用Win32Exception类型处理Win32错误代码

    .NET(C#):使用Win32Exception类型处理Win32错误代码

    2012年02月27日 ⁄ 综合 ⁄ 共 1753字 ⁄ 字号    ⁄ 评论关闭
     

    此类型在System.ComponentModel命名空间内,而不是你可能认为的System.Runtime.InteropServices命名空间内。

    Console.WriteLine(Marshal.GetLastWin32Error());
    Console.WriteLine(new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()).Message);

    但是他的父类:ExternalException,则是在System.Runtime.InteropServices命名空间内。

    image

    ExternalException的父类是SystemException(当然现在SystemException和ApplicationException该继承哪个界限已经很模糊了)。注意ExternalException多了一个ErrorCode属性返回的是父类Exception的HResult属性,同时在ExternalException的构造函数中可以设置HResult属性,但是Win32Exception并没有使用这个HResult的,Win32Exception仅设置父类的Message属性,也就是说Win32Exception中的ExternalException的ErrorCode始终是保持默认值的。

    而Win32Exception自己定义了一个属性值:NativeErrorCode,同样是int类型。Win32Exception可以设置三个属性,NativeErrorCode,Exception的Message,和Exception的InnerException属性。InnerException没有特殊的地方,前两个属性有这样的特点:

    1. 可以通过构造函数设置他们的值。

    2. 如果只设置NativeErrorCode,那么Message会是相应Win32错误代码的文字描述。

    3. 如果只设置Message,那么NativeErrorCode会是Marshal.GetLastWin32Error方法的返回值。

    4. 如果什么都不设置,那么2和3都会被应用。

    这些都是非常有用的,尤其是第2项,这个可以代替另一个Win32 API:FormatMessage,开发人员就不需要再次平台调用FormatMessage API,直接使用Win32Exception则可以。

    比如随便举一个Win32错误代码:17,代表“无法将文件移动到不同的磁盘中”(可以参考:System Error Codes

    代码:

    Console.WriteLine(new System.ComponentModel.Win32Exception(17).Message);

    输出(我的系统是英文的,在中文系统会输出中文):无法将文件移动到不同的磁盘中

    接下来试试自动调用GetLastWin32Error方法,随便试一个API比如DeleteFile API。这样定义平台调用:

    //+ using System.Runtime.InteropServices;

    [DllImport("kernel32.dll", SetLastError = true)]

    [return: MarshalAs(UnmanagedType.Bool)]

    static extern bool DeleteFile(string lpFileName);

    如果出错的话,可以一般是这样处理错误:

    //+ using System.Runtime.InteropServices;

    if (!DeleteFile("123"))

    {

        //获取错误代码

        int errorCode = Marshal.GetLastWin32Error();

        //输出错误信息

        //使用FormatMessage或者Win32Exception.Message

    }

    其实还可以更快的,就是用Win32Exception的默认构造函数:

    //+ using System.ComponentModel;

    if (!DeleteFile("123"))

        Console.WriteLine(new Win32Exception().Message);

    此时Marshal.GetLastWin32Error和Win32错误代码的描述都会被解决,于是代码会输出“文件未找到”的字样:

    The system cannot find the file specified

  • 相关阅读:
    提高效率
    kill 挂起 Apache Web Server
    /var/spool/mail/root
    https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/connections.py
    top swap
    top load average
    Difference between exit() and sys.exit() in Python
    八进制权限掩码 3位 4位 setuid setgid sticky
    以二进制和八进制方式表示文件模式
    0 lrwxrwxrwx. 1 root root 13 Nov 20 12:44 scala -> scala-2.12.4
  • 原文地址:https://www.cnblogs.com/lasthelloworld/p/4961549.html
Copyright © 2011-2022 走看看