您的位置:首页 > 编程语言 > C#

C# 写txt 文档日志

2014-06-03 14:36 176 查看

public static void ErrorLog(string mssg)

        {

            

            //string FilePath = System.Web.HttpContext.Current.Server.MapPath("log/ErrorLog.txt");

            string FilePath = MapPath("../../log/ErrorLog.txt");

                   

            try

            {

                if (File.Exists(FilePath))

                {

                    using (StreamWriter tw = File.AppendText(FilePath))

                    {

                        tw.WriteLine(DateTime.Now.ToString() + "> " + mssg);

                    }  

                }  

                else

                {

                    TextWriter tw = new StreamWriter(FilePath);

                    tw.WriteLine(DateTime.Now.ToString() + "> " + mssg);

                    tw.Flush();

                    tw.Close();

                    tw = null;

                }  

            }  

            catch (Exception)

            {

               

            }

            #endregion

        }

        public static string MapPath(string strPath)

        {

            if (HttpContext.Current != null)

            {

                return HttpContext.Current.Server.MapPath(strPath);

            }

            else //非web程序引用

            {

                strPath = strPath.Replace("/", "\\");

                if (strPath.StartsWith("\\"))

                {

                    //strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');

                    strPath = strPath.TrimStart('\\');

                }

                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);

            }

        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: