以每天的日期为txt名称,向对应的txt文件中逐次写入Log日志信息:
向textbox1中输入Log信息,点击按钮SaveInfo时,Log信息会逐次保存到对饮的.txt文件中;
using System.Text;
using System.IO;
namespace WinFormsApp_SaveInfo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_SaveInfo_Click(object sender, EventArgs e)
{
string strTemp = textBox1.Text;
recordLog(strTemp);
}
static string LogDir = Directory.GetCurrentDirectory() + "\\Log";
public static void recordLog(string info)
{
string Filename = LogDir + "//" + System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
if (!Directory.Exists(LogDir))
{
Directory.CreateDirectory(LogDir);
}
if (!File.Exists(Filename))
{
File.WriteAllText(Filename, null, Encoding.Default);
}
try
{
StreamWriter sw = File.AppendText(Filename);
sw.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " " + info);
sw.Close();
}
catch (Exception)
{
throw;
}
}
}
}