2018-01-16 22:44:35
许多程序需要记录运行日志,这就需要将程序运行记录写入本机,一般是.txt 文本或.csv 文件。具体操作如下:
一、C#
1 //加入外部输入输出的命名空间 2 using System.IO;
1 static void Main(string[] args) 2 { 3 WriteLog("白日依山尽"); 4 WriteLog("黄河入海流"); 5 WriteLog("欲穷千里目"); 6 WriteLog("更上一层楼"); 7 Console.ReadKey(); 8 } 9 static void WriteLog(string workinfo) 10 { 11 //保存运行日志到程序运行文件夹下,并以当前日期命名 12 string strpath = Directory.GetCurrentDirectory()+ @"\worklog\" + DateTime.Now.ToString("yyyyMMdd") + ".csv"; 13 //获取strpath的文件夹名称,并判断不存在是创建文件夹 14 if (!Directory.Exists(Path.GetDirectoryName(strpath))) 15 { 16 Directory.CreateDirectory(Path.GetDirectoryName(strpath)); 17 } 18 //判断文件不存在时,创建该文件 19 if (!File.Exists(strpath)) 20 { 21 File.Create(strpath).Close();//创建完毕后,需关闭该IO通道,以使后续读写可继续进行 22 } 23 //使用数据流写入StreamWriter,true表示可持续写入,Encoding.Default前系统设置的默认字符集编码方式 24 StreamWriter sw = new StreamWriter(strpath, true, Encoding.Default); 25 sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss " + workinfo)); 26 //销毁数据数据流通道 27 sw.Dispose(); 28 // 29 Console.WriteLine("写入成功"); 30 }
二、VB.NET
1 Imports System.IO '外部输出的命名空间 2 Imports System.Text '文本编码格式的命名空间
1 Sub Main() 2 WriteLog("白日依山尽") 3 WriteLog("黄河入海流") 4 WriteLog("欲穷千里目") 5 WriteLog("更上一层楼") 6 Console.ReadKey() 7 End Sub 8 Sub WriteLog(ByVal workinfo As String) 9 '保存运行日志到程序运行文件夹下,并以当前日期命名 10 Dim strpath As String = Directory.GetCurrentDirectory() & "\worklog\" & Now.ToString("yyyyMMdd") & ".csv" 11 '获取strpath的文件夹名称,并判断不存在是创建文件夹 12 If (Not Directory.Exists(Path.GetDirectoryName(strpath))) Then 13 Directory.CreateDirectory(Path.GetDirectoryName(strpath)) 14 End If 15 '判断文件不存在时,创建该文件 16 If (Not File.Exists(strpath)) Then 17 File.Create(strpath).Close() '创建完毕后,需关闭该IO通道,以使后续读写可继续进行 18 End If 19 '使用数据流写入StreamWriter,true表示可持续写入,Encoding.Default前系统设置的默认字符集编码方式 20 Dim sw As StreamWriter = New StreamWriter(strpath, True, Encoding.Default) 21 sw.WriteLine(Now.ToString("yyyy-MM--dd HH:mm:ss ") & workinfo) 22 '销毁数据数据流通道 23 sw.Dispose() 24 Console.WriteLine("写入成功") 25 End Sub
三、效果如下: