码迷,mamicode.com
首页 > Windows程序 > 详细

C# 写日志

时间:2015-07-02 01:24:50      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

class Log
    {        
        public static void Write(string str)
        {
            FileStream fs = null;
            string LogDir = Directory.GetCurrentDirectory() + "
\\log\\";
            Directory.CreateDirectory(LogDir);
            string fileName = LogDir + DateTime.Now.ToString("yyyyMMdd") + ".txt";  
           
            //将待写的入数据从字符串转换为字节数组  
            Encoding encoder = Encoding.UTF8;
            byte[] bytes = encoder.GetBytes(DateTime.Now.ToString("hh:mm:ss") + ": " + str + Environment.NewLine);  
            try  
            {
                fs = File.OpenWrite(fileName);  
                //设定书写的開始位置为文件的末尾  
                fs.Position = fs.Length;  
                //将待写入内容追加到文件末尾  
                fs.Write(bytes, 0, bytes.Length);
                // fs.Write();
            }  
            catch (Exception ex)  
            {  
                Console.WriteLine("文件打开失败{0}", ex.ToString());  
            }  
            finally  
            {  
                fs.Close();  
            }  
        }
    }

C# 写日志

标签:

原文地址:http://my.oschina.net/u/582827/blog/473109

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!