现在的位置: 首页 > 综合 > 正文

C#.NET Log操作

2013年03月14日 ⁄ 综合 ⁄ 共 2309字 ⁄ 字号 评论关闭

 

代码

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
}
}

 

抱歉!评论已关闭.