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

日志输出--C#

时间:2015-02-06 23:02:01      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//添加引用,并导入命名空间
using System.Management;
using System.Net.NetworkInformation;
using System.IO;
//日志输出类
  public void SWriter(string ipname)
        {
            string sFilePath = "D:WebTest/LogFolder/";//指定文件夹路径
            string sFileName = "LogOutPut"+DateTime.Now.ToString("dd")+".log";//指定文件
            sFileName = sFilePath + "/" + sFileName;//指定路径下的文件
            ///判断是否存在文件夹,如果不存在则创建
            if (!Directory.Exists(sFilePath))
            {
                Directory.CreateDirectory(sFilePath);
            }
            FileStream fs;//声明文件流
            StreamWriter sw;//声明写入流
            FileInfo fi=new FileInfo(sFileName);//初始化文件操作类
            ///判断是否存在文件,如果不存在则创建
            if (!fi.Exists)
            {
                fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write);
            }
            else {
                fs = new FileStream(sFileName,FileMode.Append,FileAccess.Write);
            }
            fs.Close();//凡是流(Stream)必须在最后调用.Flush();跟.Close();方法,或者图个省事用using来处理,也可以用try-catch
            using(sw = new StreamWriter(sFileName,true))
            {
                Console.SetOut(sw);//打开要写入的文件,没有这个则不会写入
                Console.WriteLine("“" + ipname + "”" + "的IP用户于" + DateTime.Now + "访问了该主页!!!");//写入内容
            }
            //StreamWriter sw = new StreamWriter(@"D:\WebTest\LogOutput.txt",true);
            //Console.SetOut(sw);
            //Console.WriteLine("“" + ipname + "”" + "的IP用户于" + DateTime.Now + "访问了该主页!!!");
            //sw.Flush();
            //sw.Close();
        }

日志输出--C#

标签:

原文地址:http://www.cnblogs.com/kevinfuture/p/4278059.html

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