using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace log文件
{
public partial class mlog : UserControl
{
FileStream LogFile;
string str_date; //log文件日期
List<string> str_list = new List<string>();
int MsgMaxLine = 300;//最大行数
public mlog()
{
InitializeComponent();
}
public void AddMsg(string MsgStr)
{
byte[] byData;
if (LogFile == null || 0 != string.Compare(str_date, DateTime.Now.ToString("yyyy-MM-dd")))
{
String str;
str = Path.GetFullPath("..") + "\\log\\";
if (!Directory.Exists(str))
{
//文件夹不存在则创建
Directory.CreateDirectory(str);
}
try
{
if (LogFile != null)
{
LogFile.Close();
LogFile = null;
}
str += DateTime.Now.ToString("yyyy-MM-dd") + ".log";
if (!File.Exists(str))
{
LogFile = new FileStream(str, FileMode.Create);
}
else
{
LogFile = new FileStream(str, FileMode.Open);
}
str_date = DateTime.Now.ToString("yyyy-MM-dd");
}
catch (Exception)
{
return;
}
}
if (LogFile != null)
{
string StrTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
MsgStr = "<" + StrTime + ">" + MsgStr + "\n";//加入log
// MsgStr = MsgStr + Environment.NewLine;//分行
LogFile.Seek(0, SeekOrigin.End);//在第一行打印
byData = System.Text.Encoding.Default.GetBytes(MsgStr);//设置格式
if (LogFile.CanWrite) LogFile.Write(byData, 0, byData.Length);
// PrintMsg = MsgStr;//传递信息给界面显示
str_list.Add(MsgStr.ToString());
richTextBox1.AppendText(MsgStr.ToString() );
// richTextBox1.SelectedText = MsgStr.ToString() ;
richTextBox1.SelectionColor = System.Drawing.Color.DarkGray;
if (richTextBox1.Lines.Count() > MsgMaxLine ) richTextBox1.Lines[0].Remove(0);
richTextBox1.SelectionStart = richTextBox1.Text.Length;
}
}
private void listBox1_Click(object sender, EventArgs e)
{
}
private void mlog_Load(object sender, EventArgs e)
{
AddMsg("tset");
}
}
}
C#写log文件
最新推荐文章于 2024-11-23 22:36:56 发布

2248

被折叠的 条评论
为什么被折叠?



