废话不多说,直接上代码,关键代码都有注释,不理解的可以留言提出.

   private static streamwriter streamwriter; //写文件  
        //将错误信息写入文件中
        public static void writeerror(string message)
        {
            try
            {
                //datetime dt = new datetime();
                string directpath = configurationmanager.appsettings["logfilepath"].tostring().trim();    //在获得文件夹路径
                if (!directory.exists(directpath))   //判断文件夹是否存在,如果不存在则创建
                {
                    directory.createdirectory(directpath);
                }
                directpath += string.format(@"\{0}.log", datetime.now.tostring("yyyy-mm-dd"));
                if (streamwriter == null)
                {
                    streamwriter = !file.exists(directpath) ? file.createtext(directpath) : file.appendtext(directpath);    //判断文件是否存在如果不存在则创建,如果存在则添加。
                }
                streamwriter.writeline("***********************************************************************");
                streamwriter.writeline(datetime.now.tostring("hh:mm:ss"));
                streamwriter.writeline("输出信息:错误信息");
                if (message != null)
                {
                    streamwriter.writeline("异常信息:\r\n" + message);
                }
            }
            finally
            {
                if (streamwriter != null)
                {
                    streamwriter.flush();
                    streamwriter.dispose();
                    streamwriter = null;
                }
            }
        }

ok,今天的分享就到这里了,有疑问的欢迎留言!