1. 程式人生 > >文件 日誌 寫入 與讀取

文件 日誌 寫入 與讀取

post 入口 頁面 ces close footer list() tostring 內容

private static string logPath = @"D:\LogS\Logs\";

public static string FloderPath
{
get
{
return logPath;
}
set
{
logPath = value;
}
}

private static object lockHelper = new object();


//簡單的寫了一個頁面

public ActionResult Logtext()
{
return View();
}

//簡單的寫了一個頁面入口提交文字
public ActionResult Add(string Text)
{
string textlog = Text;
//寫入
Write("測試:", textlog);
string fileName = "測試:" + "-" + DateTime.Now.ToString("yyyy_MM_dd") + ".log";
//讀取
var str = Read(fileName, "utf-8");

var Temp = new
{
nsuccess = false,
message = "寫入讀取成功"
};
return Json(Temp);
}


/// <summary>
/// 寫日誌
/// </summary>
/// <param name="LogType">日誌類型</param>
/// <param name="Strings">消息</param>
public static bool Write(string LogType, string str)
{
try
{
//string fileName = LogType + "-" + DateTime.Now.ToString("yyyy_MM_dd") + ".log";
if (!System.IO.Directory.Exists(FloderPath))
{
System.IO.Directory.CreateDirectory(FloderPath);
}
return Write(LogType, str, "utf-8");
}
catch
{
return false;
}
}

/// <summary>
/// 寫日誌gb2312 UTF-8
/// </summary>
/// <param name="LogType">日誌類型</param>
/// <param name="str">消息</param>
/// <param name="encoding">編碼gb2312 UTF-8</param>
public static bool Write(string LogType, string str, string encoding)
{
if (!System.IO.Directory.Exists(FloderPath))
{
System.IO.Directory.CreateDirectory(FloderPath);
}
string fileName = LogType + "-" + DateTime.Now.ToString("yyyy_MM_dd") + ".log";
bool _isTrue = false;
lock (lockHelper)
{
System.IO.FileStream f = null;
System.IO.StreamWriter f2 = null;
try
{
if (!System.IO.File.Exists(logPath + fileName)) { f = System.IO.File.Create(logPath + fileName); f.Close(); f.Dispose(); f = null; }
f2 = new System.IO.StreamWriter(logPath + fileName, true, System.Text.Encoding.GetEncoding(encoding));
f2.WriteLine("----------------------------------------header-------------------------------------");
f2.WriteLine(str);
f2.WriteLine("----------------------------------------footer-------------------------------------");
_isTrue = true;
}
catch { }
finally
{
if (f != null) { f.Close(); f.Dispose(); f = null; }
if (f2 != null) { f2.Close(); f2.Dispose(); f2 = null; }
}
}
return _isTrue;
}


/// <summary>
/// 讀取文件中的內容
/// </summary>
/// <param name="fileName">文件</param>
/// <param name="encoding">編碼gb2312 UTF-8</param>
/// <returns>ArrayList</returns>
public static ArrayList Read(string fileName, string encoding)
{
string lineText = null; ArrayList txtTextArr = new ArrayList();
if (!System.IO.File.Exists(FloderPath + fileName)) { txtTextArr = null; return txtTextArr; }

lock (lockHelper)
{
StreamReader reader = encoding.Equals("") ? new StreamReader(FloderPath + fileName) : new StreamReader(FloderPath + fileName, System.Text.Encoding.GetEncoding(encoding));
while ((lineText = reader.ReadLine()) != null)
{
txtTextArr.Add(lineText);
}

reader.Close();
reader.Dispose();
}
return txtTextArr;
}

文件 日誌 寫入 與讀取