.NET C#调用Windows操作系统函数时根据返回的错误码获取对应的错误描述信息
2022/4/1 7:21:27
本文主要是介绍.NET C#调用Windows操作系统函数时根据返回的错误码获取对应的错误描述信息,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
有时候开发经常会调用Windows自己的函数实现业务功能。这个过程中,底层函数可能会出现错误,返回的错误码类似“0xxxxxxxxxx”这样,不容易具体看到错误的问题。
Windows同样提供了方法对这些错误码进行转义为具体的错误信息描述。以下示例以.NET C#语言实现。
1.工具类
/// <summary>
/// 对需要获取错误信息码的C函数,标签上补充SetLastError = true
/// 获取错误码的方式:int errCode = Marshal.GetLastWin32Error()
/// 获取错误码对应的错误描述信息的方式:string errMsg = GetSysErrMsg(errCode);
/// </summary>
public static class ErrMsgUtils
{
#region 获取C函数错误码对应的错误信息描述
/// <summary>
/// Kernel32.dll下根据错误码获得对应的错误信息描述用方法,不推荐直接调用
/// </summary>
[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
public extern static int FormatMessage(
int flag,
ref IntPtr source,
int msgid,
int langid,
ref string buf,
int size,
ref IntPtr args);
/// <summary>
/// 获取系统错误信息描述
/// </summary>
/// <param name="errCode">系统错误码</param>
/// <returns>错误信息描述</returns>
public static string GetSysErrMsg(int errCode)
{
IntPtr tempPtr = IntPtr.Zero;
string msg = null;
FormatMessage(0x1300, ref tempPtr, errCode, 0, ref msg, 255, ref tempPtr);
return msg;
}
#endregion
}
2.调用方式
using System.Runtime.InteropServices;
if(!CallWindowsFunc(xxx))//假设CallWindowsFunc方法里调用了Windows底层函数,以静态类形式引入Windows函数头,并给函数标注[SetLastError = true]标签,返回true代表执行Windows函数成功,返回false代表执行失败
{
//可以获取操作系统对此种情况的错误码的解析内容描述
int errCode = Marshal.GetLastWin32Error();//获取错误码
string errMsg = ErrMsgUtils.GetSysErrMsg(errCode);//调用工具类获取具体的错误信息内容
}
这篇关于.NET C#调用Windows操作系统函数时根据返回的错误码获取对应的错误描述信息的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具
- 2024-01-24.NET集成IdGenerator生成分布式全局唯一ID
- 2024-01-23用CI/CD工具Vela部署Elasticsearch + C# 如何使用
- 2024-01-23.NET开源的简单、快速、强大的前后端分离后台权限管理系统