zoukankan      html  css  js  c++  java
  • c#操作文件实现日志功能

    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 }
  • 相关阅读:
    vim 编辑器
    用得到到的超方便软件
    关于 lua table表
    python 写入文件形式
    ifconfig中lo、eth0、br0、wlan0接口
    CPU:chip、core 和 processor 的关系
    lua 匹配空白符
    排序,查找(借鉴某大神的想法)
    sublime 快捷键
    获取进程的名称
  • 原文地址:https://www.cnblogs.com/beeone/p/2097344.html
Copyright © 2011-2022 走看看