推荐仅在.NET Framework中使用
简易写入日志
csharp
/// <summary>
/// 写入日志
/// </summary>
/// <param name="str">写人内容</param>
/// <param name="fileStr">自定义文件名</param>
/// <returns></returns>
private string Log(string str, string fileStr)
{
try
{
//在程序目录创建log文件
var logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
//存在则创建
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(logPath);
}
//创建指定日志文件
var FileStr = logPath + $"\\{fileStr}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.txt";
using (StreamWriter sw = File.AppendText(FileStr))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + str);
sw.Flush();
}
return FileStr;
}
catch (Exception) { return ""; }
}
简易读取日志
csharp
/// <summary>
/// 简易读取
/// </summary>
/// <param name="Path"></param>
/// <returns></returns>
private string LogStr(string Path)
{
string txt = string.Empty;
using (StreamReader sr = new StreamReader(Path))
{
string line;
while ((line = sr.ReadLine()) != null)
{
txt += line;
}
}
return txt;
}
简易调用日志
csharp
static void Main(string[] args)
{
var p = new Program();
//写入
//var pFile = p.Log("简易日志", "log");
//Console.WriteLine(pFile);
//读取
var pLogStr = p.LogStr("C:\\Users\\admin\\Desktop\\netFramework\\bin\\Debug\\log\\log_20240522140312.txt");
Console.WriteLine(pLogStr);
}
运行结果
1.写入后返回写入地址
2.根据写入地址读取日志