作用

程序异常崩溃前使用此类为进程创建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.sula.cn/101.shtml

出处:http://www.111cn.net/net/33/bae2af56ee02cd99daba9a078a311107.htm

C#程序保存dump文件的更多相关文章

  1. 使用GDB 追踪依赖poco的so程序,core dump文件分析.

    前言 在windows 下 系统核心态程序蓝屏,会产生dump文件. 用户级程序在设置后,程序崩溃也会产生dump文件.以方便开发者用windbg进行分析. so,linux 系统也有一套这样的东东- ...

  2. 【转】如何用WINDBG分析64位机上32位程序的DUMP文件

    将dump拖入到windbg中后,在command输入栏输入 .load wow64exts 回车 !sw 回车,就将windbg的dump,从64位模式切换到了32位模式,否则看到的call sta ...

  3. WinDbg抓取程序报错dump文件的方法

    程序崩溃的两种主要现象: a. 程序在运行中的时候,突然弹出错误窗口,然后点错误窗口的确定时,程序直接关闭 例如: “应用程序错误” “C++错误之类的窗口” “程序无响应” “假死”等 此种崩溃特点 ...

  4. 编写的windows程序,崩溃时产生crash dump文件的办法

    一.引言 dump文件是C++程序发生异常时,保存当时程序运行状态的文件,是调试异常程序重要的方法,所以程序崩溃时,除了日志文件,dump文件便成了我们查找错误的最后一根救命的稻草.windows程序 ...

  5. 自定义VS程序异常处理及调试Dump文件(一)

    自定义VS程序异常处理及调试Dump文件(一) 1. Dump文件 1. Dump文件介绍 Dump文件(Dump File),也叫转储文件,以.DMP为文件后缀.dump文件是进程在内存中的镜像文件 ...

  6. [JAVA]JAVA章3 如何获取及查看DUMP文件

    一.dump基本概念 在故障定位(尤其是out of memory)和性能分析的时候,经常会用到一些文件来帮助我们排除代码问题.这些文件记录了JVM运行期间的内存占用.线程执行等情况,这就是我们常说的 ...

  7. 关于崩溃报告的日志以及dump文件

    在用户使用软件的过程当中突然产生软件崩溃的问题,必须采取相关的措施去拦截崩溃产生的原因,这有助于程序员解决此类崩溃的再次发生.特别是有些难以复现的崩溃,不稳定的崩溃,更有必要去调查崩溃产生的原因.一般 ...

  8. [转]让程序在崩溃时体面的退出之Dump文件

    原文地址:http://blog.csdn.net/starlee/article/details/6630816 在我的那篇<让程序在崩溃时体面的退出之CallStack>中提供了一个在 ...

  9. dump文件定位程序崩溃代码行

    1.dump文件 2.程序对应的pdb 步骤一:安装windbg 步骤二:通过windbg打开crash dump文件 步骤三:设置pdb文件路径,即符号表路径 步骤四:运行命令!analyze -v ...

随机推荐

  1. Leetcode 1262. 可被三整除的最大和

    题目:给你一个整数数组 nums,请你找出并返回能被三整除的元素最大和. 示例 1: 输入:nums = [3,6,5,1,8] 输出:18 解释:选出数字 3, 6, 1 和 8,它们的和是 18( ...

  2. ASP.NET Core Windows服务开发技术实战演练

    一.课程介绍 人生苦短,我用.NET Core!大家都知道如果想要程序一直运行在Windows服务器上,最好是把程序写成Windows服务程序:这样程序会随着系统的自动启动而启动,自动关闭而关闭,不需 ...

  3. 《Linux就该这么学》培训笔记_ch00_认识Linux系统和红帽认证

    <Linux就该这么学>培训笔记_ch00_认识Linux系统和红帽认证 文章最后会post上书本的笔记照片. 文章主要内容: 认识开源 Linux系统的种类及优势特性 认识红帽系统及红帽 ...

  4. 集合单列--Colletion

    集合 学习集合的目标: 会使用集合存储数据 会遍历集合,把数据取出来 掌握每种集合的特性 集合和数组的区别 数组的长度是固定的.集合的长度是可变的. 数组中存储的是同一类型的元素,可以存储基本数据类型 ...

  5. go ---作用域及判断变量类型的方式。

    package main import ( "fmt" ) var v = "1, 2, 3" func main() { v := []int{1, 2, 3 ...

  6. python修改linux日志(logtamper.py)

    原作者原文:https://blog.csdn.net/qq_27446553/article/details/51434451 躲避管理员who查看 python logtamper.py -m - ...

  7. mysql给某个用户单个表权限

    CREATE USER systemselect IDENTIFIED BY 'Zbank123456';#只给查询权限 GRANT SELECT ON szkitil.zbank_businesss ...

  8. [個人紀錄] git 設定

    -- git history git config --global alias.history=log --graph --all --pretty=format:'%C(bold blue)%H% ...

  9. linux安装php nginx mysql

    linux装软件方式: systemctl status firewalld.service 查看防火墙systemctl stop firewalld.service systemctl disab ...

  10. 记一下python的method resolution order(MRO)机制

    一直用python都是拿着cookbook和库的文档直接撸,很少会把细节过得那么彻底,遇到问题才会翻文档. 今天看到这个例子的时候我突然触及了我的盲区,我不确定这样的继承层级调用super.foo() ...