一、日志文件的后台应用
1、创建一个项目=>类库(.NET Framework)
2、引用 using System.IO
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace Common { public static class FileHelper { public static void WriteLog(string log) { //获取当前目录 var baseDir = AppDomain.CurrentDomain.BaseDirectory + "/log/"; //文件名 var fileName = DateTime.Now.ToString("yyyyMMdd") + ".log"; //判断文件夹是否存在 if(!Directory.Exists(baseDir)) { //不存在,创建文件夹 Directory.CreateDirectory(baseDir); } var newPath = baseDir + fileName; //using 可以自动释放资源 using (FileStream fs=new FileStream (newPath,FileMode.Append,FileAccess.Write)) { //借助 StreamWriter 来完成对文件的写操作 using (StreamWriter sw=new StreamWriter(fs)) { sw.WriteLine(DateTime.Now + ":" + log); } } } } }
二、在控制台中引用
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Domain; using Service; using Common; namespace XiangMu_GoMai3.Controllers { public class LoginController : Controller { LoginBll loginBll = new LoginBll(); //登录视图 public ActionResult Index() { return View(); } //登录功能 [HttpPost] public ActionResult Login(string uname, string upass) { var result = loginBll.Login(uname, upass); if(result!=null) { Session["UserName"] = result.UName; //记录日志 FileHelper.WriteLog("用户名:" + uname + "登录成功"); return Json(1, JsonRequestBehavior.DenyGet); } else { //记录日志 FileHelper.WriteLog("用户名:" + uname + "登录失败"); return Json(0, JsonRequestBehavior.DenyGet); } } } }