C# 写入文件小示例


using System;
using System.Configuration;
using System.IO;

namespace ToIO
{
    public class WritLogAdapter
    {
        public static readonly WritLogAdapter Instance = new WritLogAdapter();

        public void Write(string logMessage, int path)
        {
            string strpath = "";
            switch (path)
            {
                case 1:
                    strpath = ConfigurationManager.AppSettings["WritePath"];
                    break;
                case 2:
                    strpath = ConfigurationManager.AppSettings["ReadPath"];
                    break;
                case 3:
                    strpath = ConfigurationManager.AppSettings["LogPath"];
                    break;
            }

            strpath = strpath.Replace("{Year}", DateTime.Now.Year.ToString()).Replace("{Month}", DateTime.Now.Month.ToString()).Replace("{Day}", DateTime.Now.Day.ToString());
            if (!Directory.Exists(strpath))
            {
                Directory.CreateDirectory(strpath);
            }

            string fileName = "";
            switch (path)
            {
                case 1:
                    fileName = strpath + "\\Write.txt";
                    break;
                case 2:
                    fileName = strpath + "\\Read.txt";
                    break;
                case 3:
                    fileName = strpath + "\\Log.txt";
                    break;
            }

            WriteLog(logMessage, fileName);
        }

        public void WriteLog(string logMessage, string fileName)
        {
            using (StreamWriter w = File.AppendText(fileName))
            {
                w.WriteLine("----{0}----", DateTime.Now);
                w.WriteLine("{0},", logMessage);
                w.WriteLine("");
                w.Flush();//清楚缓存
                w.Close();//关闭文件
            }
        }
    }
}

  


 

 

posted @ 2022-08-04 17:52  风儿_VIP  阅读(160)  评论(0编辑  收藏  举报