• 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 }
  • 相关阅读:
    shell if 条件语句实践
    shell函数
    透视财富增长的秘密
    kvm虚拟化实践
    Linux驱动编程--基于I2C子系统的I2C驱动
    Makefile中=、:=、+=、?=的区别
    字符设备驱动结构与开发
    驱动分类
    为什么ARM的frq中断的处理速度比较快
    Linux设备驱动01
  • 原文地址:https://www.cnblogs.com/beeone/p/2097344.html
Copyright © 2020-2023  润新知