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

  • 相关阅读:
    《真是头铁的》 回复
    今天 凌晨, 我 的 许多 帖子 (回复) 被 反相吧 吧务 删除
    《【建议】吧务同志们每个礼拜写一篇规范论文》 回复
    《有个数学模型想咨询下吧友的意见》 回复
    《请大家推荐反相吧大吧主》 回复
    复变函数 和 积分变换 就是 自己 设定 一套规则 自己 玩
    《这是等臂杠杆还是省力杠杆?》 回复
    《我的理论转帖讨论》 回复
    《数学已经明确了,0.999...与1是完全相等的》 回复
    和 @物空必能 的 对话
  • 原文地址:https://www.cnblogs.com/lasthelloworld/p/4961549.html
Copyright © 2020-2023  润新知