代碼
using System;
using System.Text;
using System.Web;
using System.IO;
using System.Collections;
using System.Threading;
namespace Pub.Class
{
/// <summary>
/// 日誌管理類
/// </summary>
public class Log
{
private static object lockHelper = new object();
#region Write/Read
/// <summary>
/// 寫日誌
/// </summary>
/// <param name="LogFileName">檔案</param>
/// <param name="Strings">訊息</param>
public static bool Write(string fileName,string str) {
return Write(fileName, str, "utf-8");
}
/// <summary>
/// 寫日誌gb2312 UTF-8
/// </summary>
/// <param name="fileName">檔案</param>
/// <param name="str">訊息</param>
/// <param name="encoding">編碼gb2312 UTF-8</param>
public static bool Write(string fileName,string str,string encoding){
bool _isTrue = false;
lock(lockHelper) {
System.IO.FileStream f = null;
System.IO.StreamWriter f2 = null;
try {
if (!System.IO.File.Exists(fileName)) { f = System.IO.File.Create(fileName); f.Close(); f.Dispose(); f = null; }
f2 = new System.IO.StreamWriter(fileName, true, System.Text.Encoding.GetEncoding(encoding));
f2.WriteLine(str);
_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 (!FileFolder.FileExists(fileName)) { txtTextArr = null; return txtTextArr; }
lock(lockHelper) {
StreamReader reader = encoding.Equals("") ? new StreamReader(fileName) : new StreamReader(fileName, System.Text.Encoding.GetEncoding(encoding));
while ((lineText = reader.ReadLine()) != null){
txtTextArr.Add(lineText);
}
reader.Close();
reader.Dispose();
}
return txtTextArr;
}
/// <summary>
/// 讀取指定檔案內容
/// </summary>
/// <param name="fileName">檔案路徑</param>
/// <param name="encoding">編碼</param>
/// <returns></returns>
public static StringBuilder ReadFile(string fileName,string encoding){
string lineText = null;StringBuilder txtTextArr = new StringBuilder();
if (!FileFolder.FileExists(fileName)) { txtTextArr = null; return txtTextArr; }
lock(lockHelper) {
StreamReader reader = encoding.Equals("") ? new StreamReader(fileName) : new StreamReader(fileName, System.Text.Encoding.GetEncoding(encoding));
while ((lineText = reader.ReadLine()) != null){
txtTextArr.Append(lineText + Environment.NewLine);
}
reader.Close();
reader.Dispose();
}
return txtTextArr;
}
#endregion
}
}