在代码中手动生成Dump文件
研究了一下,可以通过代码在应用崩溃或捕获特定异常时,手动生成dump文件。常用的是调用Windows的MiniDumpWriteDump
API。可以使用P/Invoke调用该函数,具体步骤如下:
导入必要的Windows API:
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
class MiniDump
{
[Flags]
public enum MiniDumpType
{
MiniDumpNormal = 0x00000000,
MiniDumpWithDataSegs = 0x00000001,
MiniDumpWithFullMemory = 0x00000002,
MiniDumpWithHandleData = 0x00000004,
MiniDumpFilterMemory = 0x00000008,
MiniDumpScanMemory = 0x00000010,
MiniDumpWithUnloadedModules = 0x00000020,
MiniDumpWithIndirectlyReferencedMemory = 0x00000040,
MiniDumpFilterModulePaths = 0x00000080,
MiniDumpWithProcessThreadData = 0x00000100,
MiniDumpWithPrivateReadWriteMemory = 0x00000200,
MiniDumpWithoutOptionalData = 0x00000400,
MiniDumpWithFullMemoryInfo = 0x00000800,
MiniDumpWithThreadInfo = 0x00001000,
MiniDumpWithCodeSegs = 0x00002000,
MiniDumpWithoutAuxiliaryState = 0x00004000,
MiniDumpWithFullAuxiliaryState = 0x00008000,
MiniDumpWithPrivateWriteCopyMemory = 0x00010000,
MiniDumpIgnoreInaccessibleMemory = 0x00020000,
MiniDumpWithTokenInformation = 0x00040000
}
[DllImport("dbghelp.dll", SetLastError = true)]
static extern bool MiniDumpWriteDump(
IntPtr hProcess,
int processId,
IntPtr hFile,
MiniDumpType dumpType,
IntPtr exceptionParam,
IntPtr userStreamParam,
IntPtr callbackParam);
public static void WriteDump(string dumpFilePath)
{
using (var fs = new FileStream(dumpFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
Process process = Process.GetCurrentProcess();
bool success = MiniDumpWriteDump(
process.Handle,
process.Id,
fs.SafeFileHandle.DangerousGetHandle(),
MiniDumpType.MiniDumpWithFullMemory,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero);
if (!success)
{
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
}
}
}
}
调用生成dump文件: 在你的程序中可以在捕获异常时调用这个方法:
try
{
// 代码可能抛出异常
}
catch (Exception ex)
{
// 发生异常时生成dump
MiniDump.WriteDump("C:\\Dumps\\crashdump.dmp");
throw; // 可以选择继续抛出异常或处理异常
}
还可以捕获未处理的异常,生成dump
AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
Exception e = (Exception)args.ExceptionObject;
MiniDump.WriteDump("C:\\Dumps\\unhandled_exception.dmp");
};
这样,当未捕获的异常导致应用崩溃时,dump文件就会自动生成。