Files
Web_FaceValidator_Dev/LogHelper.cs

122 lines
3.4 KiB
C#
Raw Normal View History

2025-11-26 11:14:33 +08:00
using System;
using System.IO;
using System.Text;
namespace BLV_API
{
/// <summary>
/// 日志辅助类
/// </summary>
public static class LogHelper
{
public static string GetApplicationPath()
{
return AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
}
private static string ExePath =GetApplicationPath();
/// <summary>
/// 日志写入到批定的文件路径下
/// </summary>
/// <param name="msg"></param>
public static void WriteLog(string msg)
{
string path = ExePath + "\\logs\\" + DateTime.Now.ToString("yyyyMMdd") + ".log";
msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":\t " + msg + Environment.NewLine;
WriteLog(path, msg, true);
}
/// <summary>
/// 把数据写入指定的文件里
/// </summary>
/// <param name="path">文件路径(包括文件名称)</param>
/// <param name="msg">写入内容</param>
/// <param name="append">是否追加</param>
public static void WriteLog(string path, string msg, bool append, bool needHidden = false)
{
string folder = Path.GetDirectoryName(path);
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
StreamWriter sw = null;
try
{
sw = new StreamWriter(path, append, Encoding.Unicode);
sw.WriteLine(msg);
}
catch (Exception)
{
}
finally
{
if (sw != null)
{
sw.Close();
}
}
if (needHidden)
{
File.SetAttributes(path, FileAttributes.Hidden);//设置添加隐藏文件夹
}
}
/// <summary>
/// 把数据写入指定的文件里
/// </summary>
/// <param name="path"></param>
/// <param name="msg"></param>
public static void WriteLog(string path, byte[] msg)
{
string folder = Path.GetDirectoryName(path);
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
FileStream fs = null;
try
{
fs = new FileStream(path, FileMode.Append, FileAccess.Write);
fs.Write(msg, 0, msg.Length);
}
catch (Exception)
{
}
finally
{
if (fs != null)
{
fs.Close();
}
}
}
/// <summary>
/// 读取文件内容
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string ReadLog(string path)
{
if (File.Exists(path))
{
StreamReader sr = null;
try
{
sr = new StreamReader(path);
return sr.ReadToEnd();
}
catch (Exception)
{
}
finally
{
if (sr != null)
{
sr.Close();
}
}
}
return "";
}
}
}