天天看点

写日志文件

using system;

using system.collections.generic;

using system.linq;

using system.text;

using system.io;

namespace consoleapplication42

{   //某个项目,需要写日志到系统目录下的siyktlog,日志名称是以当天时间为文件名,写日志时,准确地写入当时时间日期,精确到毫秒

    class program

    {

        static void main(string[] args)

        {

            datetime dt = datetime.now;

            //测试siyktlog文件夹

            string syspath = environment.getfolderpath(environment.specialfolder.system);

            string siyktlogpath=syspath+"";

            if (!directory.exists(siyktlogpath))

            {

                directory.createdirectory(siyktlogpath);

            }

            //测试当日日志文件

            string logfilename =siyktlogpath +"\\"+ dt.toshortdatestring() +".log";

            if (!file.exists(logfilename))

               filestream tempfs = file.create(logfilename); 

               tempfs.close();   //要记得及时关闭,否则下面会报错

            //测试文件写入

            filestream fs = new filestream(logfilename, filemode.append);

            streamwriter sw = new streamwriter(fs);

            string strtime=string.format("{0:yyyy-mm-dd hh:mm:ss.ffff:}", dt);

            sw.write(strtime);

            sw.writeline("第一次测试");

            sw.close();

            console.readkey();

        }

    }

}

继续阅读