代码改变世界

c# 一个记录日志的通用方法

2016-05-10 14:44  newbirth  阅读(1032)  评论(0编辑  收藏  举报
 public static string WriteFile(string strText, string path)
        {
            Encoding code = Encoding.GetEncoding("gb2312");
            StreamWriter sw = null;
            string filename = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            try
            {
                string fullpath = System.IO.Path.Combine(path, filename);
                sw = new StreamWriter(fullpath, true, code);
                sw.Write("[" + DateTime.Now.ToString() + "]\r\n-----------------------------\r\n" + strText + "\r\n");
                sw.Flush();
            }
            catch (Exception ex)
            {
                //HttpContext.Current.Response.Write(ex.Message);
                //HttpContext.Current.Response.End();
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
            }
            return filename;
        }