一位程序员,比较帅的那种

0%

C# 生成Log文件

写了个Log类实现带时间戳的Log out, 代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
namespace My_Space
{
using System;
using System.IO;
class Log
{
private string logFile;
private StreamWriter writer;
private FileStream fileStream = null;

public Log(string fileName)
{
logFile = fileName;
CreateDirectory(logFile);
}

public void LogOut(string info)
{
try
{
FileInfo fileInfo = new FileInfo(logFile);
if (!fileInfo.Exists)
{
fileStream = fileInfo.Create();
writer = new StreamWriter(fileStream);
}
else
{
fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write);
writer = new StreamWriter(fileStream);
}
writer.WriteLine("@" + DateTime.Now + "#" + info + ";");
}
finally
{
if (writer != null)
{
writer.Close();
writer.Dispose();
fileStream.Close();
fileStream.Dispose();
}
}
}

private void CreateDirectory(string filePath)
{
DirectoryInfo directoryInfo = Directory.GetParent(filePath);
if (!directoryInfo.Exists)
{
directoryInfo.Create();
}
}

public static void ReadLog(string logPath, out string dataRead)
{
StreamReader sR1 = new StreamReader(logPath);
try
{
dataRead = sR1.ReadToEnd();
}
catch (Exception)
{
throw;
}
}
}
}