.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);//调用工具类获取具体的错误信息内容
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义