C#程序保存dump文件
作用
程序异常崩溃前使用此类为进程创建DUMP文件,之后可以使用WinDbg等工具进行分析。
辅助类代码
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices; namespace Infrastructure
{
public static class MiniDump
{
// Taken almost verbatim from http://blog.kalmbach-software.de/2008/12/13/writing-minidumps-in-c/
[Flags]
public enum Option : uint
{
// From dbghelp.h:
Normal = 0x00000000,
WithDataSegs = 0x00000001,
WithFullMemory = 0x00000002,
WithHandleData = 0x00000004,
FilterMemory = 0x00000008,
ScanMemory = 0x00000010,
WithUnloadedModules = 0x00000020,
WithIndirectlyReferencedMemory = 0x00000040,
FilterModulePaths = 0x00000080,
WithProcessThreadData = 0x00000100,
WithPrivateReadWriteMemory = 0x00000200,
WithoutOptionalData = 0x00000400,
WithFullMemoryInfo = 0x00000800,
WithThreadInfo = 0x00001000,
WithCodeSegs = 0x00002000,
WithoutAuxiliaryState = 0x00004000,
WithFullAuxiliaryState = 0x00008000,
WithPrivateWriteCopyMemory = 0x00010000,
IgnoreInaccessibleMemory = 0x00020000,
ValidTypeFlags = 0x0003ffff,
} enum ExceptionInfo
{
None,
Present
} //typedef struct _MINIDUMP_EXCEPTION_INFORMATION {
// DWORD ThreadId;
// PEXCEPTION_POINTERS ExceptionPointers;
// BOOL ClientPointers;
//} MINIDUMP_EXCEPTION_INFORMATION, *PMINIDUMP_EXCEPTION_INFORMATION;
[StructLayout(LayoutKind.Sequential, Pack = 4)] // Pack=4 is important! So it works also for x64!
struct MiniDumpExceptionInformation
{
public uint ThreadId;
public IntPtr ExceptionPointers;
[MarshalAs(UnmanagedType.Bool)]
public bool ClientPointers;
} //BOOL
//WINAPI
//MiniDumpWriteDump(
// __in HANDLE hProcess,
// __in DWORD ProcessId,
// __in HANDLE hFile,
// __in MINIDUMP_TYPE DumpType,
// __in_opt PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
// __in_opt PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
// __in_opt PMINIDUMP_CALLBACK_INFORMATION CallbackParam
// );
// Overload requiring MiniDumpExceptionInformation
[DllImport("dbghelp.dll", EntryPoint = "MiniDumpWriteDump", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] static extern bool MiniDumpWriteDump(IntPtr hProcess, uint processId, SafeHandle hFile, uint dumpType, ref MiniDumpExceptionInformation expParam, IntPtr userStreamParam, IntPtr callbackParam); // Overload supporting MiniDumpExceptionInformation == NULL
[DllImport("dbghelp.dll", EntryPoint = "MiniDumpWriteDump", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
static extern bool MiniDumpWriteDump(IntPtr hProcess, uint processId, SafeHandle hFile, uint dumpType, IntPtr expParam, IntPtr userStreamParam, IntPtr callbackParam); [DllImport("kernel32.dll", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)]
static extern uint GetCurrentThreadId(); static bool Write(SafeHandle fileHandle, Option options, ExceptionInfo exceptionInfo)
{
Process currentProcess = Process.GetCurrentProcess();
IntPtr currentProcessHandle = currentProcess.Handle;
uint currentProcessId = (uint)currentProcess.Id;
MiniDumpExceptionInformation exp;
exp.ThreadId = GetCurrentThreadId();
exp.ClientPointers = false;
exp.ExceptionPointers = IntPtr.Zero;
if (exceptionInfo == ExceptionInfo.Present)
{
exp.ExceptionPointers = Marshal.GetExceptionPointers();
}
return exp.ExceptionPointers == IntPtr.Zero ? MiniDumpWriteDump(currentProcessHandle, currentProcessId, fileHandle, (uint)options, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) : MiniDumpWriteDump(currentProcessHandle, currentProcessId, fileHandle, (uint)options, ref exp, IntPtr.Zero, IntPtr.Zero);
} static bool Write(SafeHandle fileHandle, Option dumpType)
{
return Write(fileHandle, dumpType, ExceptionInfo.None);
} public static Boolean TryDump(String dmpPath, Option dmpType=Option.Normal)
{
var path = Path.Combine(Environment.CurrentDirectory, dmpPath);
var dir = Path.GetDirectoryName(path);
if (dir != null && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
using (var fs = new FileStream(path, FileMode.Create))
{
return Write(fs.SafeFileHandle, dmpType);
}
}
}
}
提示
对于Windows Form程序,可以利用AppDomain的UnhandledException事件。以下示例:
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException +=new UnhandledExceptionEventHandler((obj,args)=> MiniDump.TryDump("error.dmp")); Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
出处:https://www.cnblogs.com/beta2013/archive/2011/08/15/3377333.html
==============================================================================
windbg 这个工具可以手动的来抓dump文件,如果你想你的程序智能一些,当遇到你开发的程序crash时,你想程序自己抓到dump文件,然后你去分析就可以。最近我刚好遇到这样一个事情,所以找了找,借助网络和论坛的朋友,才完成了这样一个事情。MiniDumpWriteDump 这个win32 api 可以完成这样一个事情。因为现在使用的是c#,所以封装了一下,本人对托管代码调用那些win api也不是很了解。所以借助了一些朋友来帮忙。
我就 直接贴代码出来吧,运行一下 就知道了,但到目前位置 我还么有对这个测试程序抓到的dump进行过分析。以后在分析吧,现在的机器上没有环境。
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using System.Threading;
namespace MiniDump
...{
class Program
...{
static void Main(string[] args)
...{
try
...{
string a = "";
a = null;
if (a.ToString() == "")
Console.WriteLine("a is 1");
}
catch
...{
MiniDump.TryDump("c:MiniDmp.dmp", MiniDump.MiniDumpType.WithFullMemory);
}
Console.ReadKey();
}
}
/**////
/// 该类要使用在windows 5.1 以后的版本,如果你的windows很旧,就把Windbg里面的dll拷贝过来,一般都没有问题
/// DbgHelp.dll 是windows自带的 dll文件 。
///
public static class MiniDump
...{
/**//*
* 导入DbgHelp.dll
*/
[DllImport("DbgHelp.dll")]
private static extern Boolean MiniDumpWriteDump(
IntPtr hProcess,
Int32 processId,
IntPtr fileHandle,
MiniDumpType dumpType,
ref MinidumpExceptionInfo excepInfo,
IntPtr userInfo,
IntPtr extInfo );
/**//*
* MINIDUMP_EXCEPTION_INFORMATION 这个宏的信息
*/
struct MinidumpExceptionInfo
...{
public Int32 ThreadId;
public IntPtr ExceptionPointers;
public Boolean ClientPointers;
}
/**//*
* 自己包装的一个函数
*/
public static Boolean TryDump(String dmpPath, MiniDumpType dmpType)
...{
//使用文件流来创健 .dmp文件
using (FileStream stream = new FileStream(dmpPath, FileMode.Create))
...{
//取得进程信息
Process process = Process.GetCurrentProcess();
// MINIDUMP_EXCEPTION_INFORMATION 信息的初始化
MinidumpExceptionInfo mei = new MinidumpExceptionInfo();
mei.ThreadId = Thread.CurrentThread.ManagedThreadId;
mei.ExceptionPointers = Marshal.GetExceptionPointers();
mei.ClientPointers = true;
//这里调用的Win32 API
Boolean res = MiniDumpWriteDump(
process.Handle,
process.Id,
stream.SafeFileHandle.DangerousGetHandle(),
dmpType,
ref mei,
IntPtr.Zero,
IntPtr.Zero);
//清空 stream
stream.Flush();
stream.Close();
return res;
}
}
public enum MiniDumpType
...{
None = 0x00010000,
Normal = 0x00000000,
WithDataSegs = 0x00000001,
WithFullMemory = 0x00000002,
WithHandleData = 0x00000004,
FilterMemory = 0x00000008,
ScanMemory = 0x00000010,
WithUnloadedModules = 0x00000020,
WithIndirectlyReferencedMemory = 0x00000040,
FilterModulePaths = 0x00000080,
WithProcessThreadData = 0x00000100,
WithPrivateReadWriteMemory = 0x00000200,
WithoutOptionalData = 0x00000400,
WithFullMemoryInfo = 0x00000800,
WithThreadInfo = 0x00001000,
WithCodeSegs = 0x00002000
}
}
}
出处:http://www.111cn.net/net/33/bae2af56ee02cd99daba9a078a311107.htm
C#程序保存dump文件的更多相关文章
- 使用GDB 追踪依赖poco的so程序,core dump文件分析.
前言 在windows 下 系统核心态程序蓝屏,会产生dump文件. 用户级程序在设置后,程序崩溃也会产生dump文件.以方便开发者用windbg进行分析. so,linux 系统也有一套这样的东东- ...
- 【转】如何用WINDBG分析64位机上32位程序的DUMP文件
将dump拖入到windbg中后,在command输入栏输入 .load wow64exts 回车 !sw 回车,就将windbg的dump,从64位模式切换到了32位模式,否则看到的call sta ...
- WinDbg抓取程序报错dump文件的方法
程序崩溃的两种主要现象: a. 程序在运行中的时候,突然弹出错误窗口,然后点错误窗口的确定时,程序直接关闭 例如: “应用程序错误” “C++错误之类的窗口” “程序无响应” “假死”等 此种崩溃特点 ...
- 编写的windows程序,崩溃时产生crash dump文件的办法
一.引言 dump文件是C++程序发生异常时,保存当时程序运行状态的文件,是调试异常程序重要的方法,所以程序崩溃时,除了日志文件,dump文件便成了我们查找错误的最后一根救命的稻草.windows程序 ...
- 自定义VS程序异常处理及调试Dump文件(一)
自定义VS程序异常处理及调试Dump文件(一) 1. Dump文件 1. Dump文件介绍 Dump文件(Dump File),也叫转储文件,以.DMP为文件后缀.dump文件是进程在内存中的镜像文件 ...
- [JAVA]JAVA章3 如何获取及查看DUMP文件
一.dump基本概念 在故障定位(尤其是out of memory)和性能分析的时候,经常会用到一些文件来帮助我们排除代码问题.这些文件记录了JVM运行期间的内存占用.线程执行等情况,这就是我们常说的 ...
- 关于崩溃报告的日志以及dump文件
在用户使用软件的过程当中突然产生软件崩溃的问题,必须采取相关的措施去拦截崩溃产生的原因,这有助于程序员解决此类崩溃的再次发生.特别是有些难以复现的崩溃,不稳定的崩溃,更有必要去调查崩溃产生的原因.一般 ...
- [转]让程序在崩溃时体面的退出之Dump文件
原文地址:http://blog.csdn.net/starlee/article/details/6630816 在我的那篇<让程序在崩溃时体面的退出之CallStack>中提供了一个在 ...
- dump文件定位程序崩溃代码行
1.dump文件 2.程序对应的pdb 步骤一:安装windbg 步骤二:通过windbg打开crash dump文件 步骤三:设置pdb文件路径,即符号表路径 步骤四:运行命令!analyze -v ...
随机推荐
- [记录]安装.Net Framework 4.6.2时出现“无法建立到信任根颁发机构的证书链”解决方法
在安装Microsoft .NET Framework 4.6.2脱机包时提示 无法建立到信任根颁发机构的证书链 实际上是要安装一个根证书.解决方案如下(因无法贴链接,可百度搜索“mamicode.c ...
- 本周使用angular7所遇到的一些问题
前言 本周在使用angular7所遇到的一些问题,学习是不断的循序渐进的过程,在本周完成对应的工作后,也要抽出一些时间用来学习,比较我们公司10点上班,我一般9点就会到,在这一个小时内看看博客,写写笔 ...
- Windows忘记BIOS密码/操作系统密码处理办法汇总
一.说明 关于电脑,在大学之前是知之甚少的.举几个例子,一是刚上大学时我还是分不清主机和显示器哪个才是电脑:二是应该是大一上学期陪窒友Z到电科买电脑,我问导购员XP和Win7什么关系----我一直怀疑 ...
- ElasticSearch中的JVM性能调优
ElasticSearch中的JVM性能调优 前一段时间被人问了个问题:在使用ES的过程中有没有做过什么JVM调优措施? 在我搭建ES集群过程中,参照important-settings官方文档来的, ...
- java解析复杂的json字符串
Java解析Json字符串--复杂对象(方法一) { "name": "三班", "students": [ { "age&q ...
- Scala Types 1
在 Scala 中所有值都有一种对应的类型 单例类型 形式:value.type,返回类型 value / null 场景1:链式API调用时的类型指定 class Super { def m1(t: ...
- UDP比TCP好用的优势
网络带宽环境变好 在2007年至2015年间,网络的带宽飞速发展,从1.5Mbps的带宽增加到5.1Mbps的带宽,足足增加了4倍,网络环境快速.稳定,所以UDP的丢包率 下降至5%以下,越来越好的网 ...
- laravel 5.5 仓库模式 文件之间接口与实现操作
仓库模式 最直接的意思就是: Eloquent数据(数据库)查询 方便快捷,简单明了.自己怎么写的,就怎么去调用,完全ok~ 本质意思: 仓库就像是业务内部的数据对象集合,负责协调业务和数据映射层之 ...
- 获取html 中的内容 将前台的数据获取到后台 用 jquery 生成一个 form表单 提交数据
使用js创建一个form表单 ,使用post上传到后台中 下面是代码.在获取html内容的时候使用了js节点来获取内容. parent:父节点.上一级的节点 siblings:兄弟节点.同一级别的节点 ...
- 锤子剪刀布pat-1018
题目描述 大家应该都会玩“锤子剪刀布”的游戏:现给出两人的交锋记录,请统计双方的胜.平.负次数,并且给出双方分别出什么手势的胜算最大. 输入描述: 输入第1行给出正整数N(<=105),即双方交 ...