.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);//呼叫工具類獲取具體的錯誤資訊內容
}