.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

转载于:https://www.cnblogs.com/lasthelloworld/p/4961549.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值