注册表,以及记录当前调用方法的基本信息的代码

public class TestStackTrace
    {
        List<object> paramValueItems = new List<object>();
        public void TestMethod(int num,string msg) 
        {
            //注册表的写入
            RegistryKey rk = Registry.LocalMachine;
            rk.SetValue("LOLRegister", "Do");
            //记录方法参数的值
            paramValueItems.Clear();
            paramValueItems.Add(num);
            paramValueItems.Add(msg);

            WriteLog(paramValueItems);

            num += num;
            msg = num.ToString() + "hello word";
        }
        public void WriteLog(List<object> items)
        {
            try
            {
                //如果可以输出日志,就执行
                //if (IsEnableOutPutLog == true)
                //{
                    StackTrace st = new StackTrace(true);
                    //这个括号里面的参数从0开始,0就是自己,1就是上一个
                    MethodBase methodName = st.GetFrame(1).GetMethod();
                    //得到参数集合
                    ParameterInfo[] paramInfo = st.GetFrame(1).GetMethod().GetParameters();
                    //文件路径
                    string fileName = "MethodInfoLog.txt";

                    //定义文件信息对象
                    FileInfo finfo = new FileInfo(fileName);

                    //判断文件是否存在以及是否大于2M 2048000
                    if (finfo.Exists && finfo.Length > 2048000)
                    {
                        try
                        {
                            //删除该文件
                            finfo.Delete();
                        }
                        catch (Exception e)
                        {

                        }

                    }
                    using (StreamWriter writer = new StreamWriter(fileName, true, System.Text.Encoding.UTF8, 1024))
                    {
                        writer.WriteLine("方法名称:" + methodName.Name);
                        writer.WriteLine("调用时间: " + DateTime.Now);
                        writer.WriteLine("--------------------------------------------------------------------");
                        for (int i = 0; i < items.Count; i++)
                        {
                            writer.WriteLine("参数名称:" + paramInfo[i].Name);
                            writer.WriteLine("参数类型:" + paramInfo[i].ParameterType);
                            writer.WriteLine("参数值:" + items[i].ToString());
                            writer.WriteLine("参数位置: " + paramInfo[i].Position);
                            writer.WriteLine(String.Empty);
                            writer.WriteLine("*********************************************************************");
                            writer.Flush();
                            writer.Close();
                        }

                    }

                //}
            }
            catch (Exception ex)
            {
                //WriteLog(ex, "方法记录出现异常!");
            }
        }

 

posted @ 2015-05-11 17:24  洛晨随风  阅读(187)  评论(0编辑  收藏  举报