导航

c#操作文件实现日志功能

Posted on 2011-07-04 13:48  beeone  阅读(1384)  评论(0编辑  收藏  举报
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using System.IO;
9
10 namespace LogDemo
11 {
12 public partial class Form1 : Form
13 {
14 public Form1()
15 {
16 InitializeComponent();
17 }
18 /// <summary>
19 /// 操作文件实现日志
20 /// </summary>
21 /// <param name="msg">日志内容</param>
22 /// <param name="lonPath">存放日志的目录,如果想默认存在项目的Debag下,请输入Null</param>
23 private void logger(String msg,string lonPath)
24 {
25 string LogPath = null;
26 if (lonPath != null)
27 {
28 LogPath = lonPath;
29 }
30 else
31 {
32 LogPath =Application.StartupPath;
33 }
34 string filePath = LogPath + "\\" + DateTime.Now.Year.ToString()+"" + DateTime.Now.Month.ToString()+"";
35 string fileName = DateTime.Now.Day.ToString() + "" + ".Log";
36 string filePathAll = filePath + "\\" + fileName;
37 if (!System.IO.Directory.Exists(filePath))
38 {
39 System.IO.Directory.CreateDirectory(filePath);
40 }
41 FileStream filestream = new FileStream(filePathAll, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
42 StreamWriter writer = new StreamWriter(filestream, System.Text.Encoding.Default);
43 writer.BaseStream.Seek(0, SeekOrigin.End);
44 writer.WriteLine("{0} {1}", DateTime.Now.TimeOfDay , msg);
45 writer.Flush();
46 writer.Close();
47 filestream.Close();
48 }
49
50 //测试方法
51 private void button1_Click(object sender, EventArgs e)
52 {
53 byte str=0 ;
54
55 try
56 {
57 if (true)
58 {
59 str = (byte)Convert.ToSByte(600);
60 }
61 else
62 {
63 str = (byte)Convert.ToSByte(500);
64 }
65 }
66 catch(Exception ex)
67 {
68 logger(ex.Message,null);
69 }
70 }
71 }
72 }