• .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

  • 相关阅读:
    Spring 学习笔记
    Java Web整合开发(33) -- SSH和SSJ
    2、常用操作
    jsonp使用
    PHP curl 封装 GET及POST方法很不错的
    浅谈CSRF攻击方式 转
    谷歌插件请求ci 解决CI框架的Disallowed Key Characters错误提示
    phpstorm10.0.3 下载与激活
    Mysql全文搜索match against的用法
    CentOS 6.4下编译安装MySQL 5.6.14 (转)
  • 原文地址:https://www.cnblogs.com/lasthelloworld/p/4961549.html
Copyright © 2020-2023  润新知