[笔记]C#在指定目录中写Log文字档

新增类别txtLog.cs

 public class txtLog    {        private static String logPath = "C:\\TEST\\log"; //Log目录               public  void WriteLog(String logMsg)        {            //档案名称 使用现在日期            String logFileName = DateTime.Now.Year.ToString() + int.Parse(DateTime.Now.Month.ToString()).ToString("00") + int.Parse(DateTime.Now.Day.ToString()).ToString("00") + ".txt";                        //Log档内的时间 使用现在时间            String nowTime = int.Parse(DateTime.Now.Hour.ToString()).ToString("00") + ":" + int.Parse(DateTime.Now.Minute.ToString()).ToString("00") + ":" + int.Parse(DateTime.Now.Second.ToString()).ToString("00");            if (!Directory.Exists(logPath))            {                //建立资料夹                Directory.CreateDirectory(logPath);            }            if (!File.Exists(logPath + "\\" + logFileName))            {                //建立档案                File.Create(logPath + "\\" + logFileName).Close();            }            using (StreamWriter sw = File.AppendText(logPath + "\\" + logFileName))            {                //WriteLine为换行                 sw.Write(nowTime + "---->");                sw.WriteLine(logMsg);                sw.WriteLine("");            }        }    }

//建立档案处须加上.Close(); 否则会跳错误:
System.IO.IOException: '由于另一个处理序正在使用档案'C:\TEST\log\xxxxxxxx.txt',所以无法存取该档案。'

因所参考网路上的文章没有加上,所以纪录一下


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章