如何保存C#中的日志?(How to keep logs in C#?)

编程入门 行业动态 更新时间:2024-10-26 08:25:51
如何保存C#中的日志?(How to keep logs in C#?)

这是一个用C#编写的WinForm。 假设我在我选择的目录中生成一个随机命名的文本文件。 当第一次单击该按钮时,我将文本框中包含的数据写入该文本文件。 如果用户想要对文本框中的不同数据执行相同的操作,则单击按钮应将新数据写入文本文件而不会丢失旧数据。 这就像保存日志一样,这可能吗?

我的代码是这样的:

private readonly Random setere = new Random(); private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private string RandomString() { char[] buffer = new char[5]; for (int i = 0; i < 5; i++) { buffer[i] = chars[setere.Next(chars.Length)]; } return new string(buffer); } private void button1_Click(object sender, EventArgs e) { DialogResult dia = MessageBox.Show("Wanna continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dia == DialogResult.Yes) { StreamWriter wFile = new StreamWriter("C:\\Users\\Ece\\Documents\\Testings\\" + RandomString() + ".txt"); wFile.WriteLine("Name Surname:" + text1.Text + text2.Text); wFile.WriteLine("Other:" + text3.Text + text4.Text); wFile.WriteLine("Money:" + textBox1.Text + " TL."); wFile.WriteLine("*************************************"); wFile.Close(); } else { return; } }

This is a WinForm written in C#. Lets say I'm generating a random named text file in my selected directory. When the button is clicked teh first time, i write the data contained in the textboxes into that text file. If the user wants to do the same thing with different data in the textboxes then the click on the button should write the new data into the text file without losing the old data. It's like keeping logs, is this possible?

My code is like:

private readonly Random setere = new Random(); private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private string RandomString() { char[] buffer = new char[5]; for (int i = 0; i < 5; i++) { buffer[i] = chars[setere.Next(chars.Length)]; } return new string(buffer); } private void button1_Click(object sender, EventArgs e) { DialogResult dia = MessageBox.Show("Wanna continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dia == DialogResult.Yes) { StreamWriter wFile = new StreamWriter("C:\\Users\\Ece\\Documents\\Testings\\" + RandomString() + ".txt"); wFile.WriteLine("Name Surname:" + text1.Text + text2.Text); wFile.WriteLine("Other:" + text3.Text + text4.Text); wFile.WriteLine("Money:" + textBox1.Text + " TL."); wFile.WriteLine("*************************************"); wFile.Close(); } else { return; } }

最满意答案

看看使用这样的东西:

StreamWriter fw = new StreamWriter(@"C:\Logs\MyFile.txt",true); fw.WriteLine("Some Message" + Environment.Newline); fw.Flush(); fw.Close();

希望有所帮助。 有关更多信息,请参阅MSDN StreamWriter

更新:删除旧示例

此外,如果您尝试创建一个唯一的文件,您可以使用Path.GetRandomFileName()再次从MSDN Books:

GetRandomFileName方法返回加密强大的随机字符串,可用作文件夹名称或文件名。

更新在下面添加了一个Logger类示例

在项目中添加一个新类并添加以下行(这是3.0类型语法,因此如果创建2.0版本则可能需要调整)

using System; using System.IO; namespace LogProvider { // // Example Logger Class // public class Logging { public static string LogDir { get; set; } public static string LogFile { get; set; } private static readonly Random setere = new Random(); private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public Logging() { LogDir = null; LogFile = null; } public static string RandomFileName() { char[] buffer = new char[5]; for (int i = 0; i < 5; i++) { buffer[i] = chars[setere.Next(chars.Length)]; } return new string(buffer); } public static void AddLog(String msg) { String tstamp = Convert.ToString(DateTime.Now.Day) + "/" + Convert.ToString(DateTime.Now.Month) + "/" + Convert.ToString(DateTime.Now.Year) + " " + Convert.ToString(DateTime.Now.Hour) + ":" + Convert.ToString(DateTime.Now.Minute) + ":" + Convert.ToString(DateTime.Now.Second); if(LogDir == null || LogFile == null) { throw new ArgumentException("Null arguments supplied"); } String logFile = LogDir + "\\" + LogFile; String rmsg = tstamp + "," + msg; StreamWriter sw = new StreamWriter(logFile, true); sw.WriteLine(rmsg); sw.Flush(); sw.Close(); } } }

将其添加到您的表单onload事件

LogProvider.Logging.LogDir = "C:\\Users\\Ece\\Documents\\Testings"; LogProvider.Logging.LogFile = LogProvider.Logging.RandomFileName();

现在将按钮单击事件调整为如下所示:

DialogResult dia = MessageBox.Show("Wanna continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dia == DialogResult.Yes) { StringBuilder logMsg = new StringBuilder(); logMsg.Append("Name Surname:" + text1.Text + text2.Text + Environment.NewLine); logMsg.Append("Other:" + text3.Text + text4.Text + Environment.NewLine); logMsg.Append("Money:" + textBox1.Text + " TL." + Environment.NewLine); logMsg.Append("*************************************" + Environment.NewLine); LogProvider.Logging.AddLog(logMsg.ToString()); } else { return; }

现在,您应该只在应用程序运行的整个时间创建一个文件,并且每次单击按钮时都会记录到该文件。

Have a look at using something like this:

StreamWriter fw = new StreamWriter(@"C:\Logs\MyFile.txt",true); fw.WriteLine("Some Message" + Environment.Newline); fw.Flush(); fw.Close();

Hope that helps. See MSDN StreamWriter for more information

Updated: Removed old example

Also if you are trying to create a unique file you can use Path.GetRandomFileName() Again from the MSDN Books:

The GetRandomFileName method returns a cryptographically strong, random string that can be used as either a folder name or a file name.

UPDATED: Added a Logger class example below

Add a new class to your project and add the following lines (this is 3.0 type syntax so you may have to adjust if creating a 2.0 version)

using System; using System.IO; namespace LogProvider { // // Example Logger Class // public class Logging { public static string LogDir { get; set; } public static string LogFile { get; set; } private static readonly Random setere = new Random(); private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public Logging() { LogDir = null; LogFile = null; } public static string RandomFileName() { char[] buffer = new char[5]; for (int i = 0; i < 5; i++) { buffer[i] = chars[setere.Next(chars.Length)]; } return new string(buffer); } public static void AddLog(String msg) { String tstamp = Convert.ToString(DateTime.Now.Day) + "/" + Convert.ToString(DateTime.Now.Month) + "/" + Convert.ToString(DateTime.Now.Year) + " " + Convert.ToString(DateTime.Now.Hour) + ":" + Convert.ToString(DateTime.Now.Minute) + ":" + Convert.ToString(DateTime.Now.Second); if(LogDir == null || LogFile == null) { throw new ArgumentException("Null arguments supplied"); } String logFile = LogDir + "\\" + LogFile; String rmsg = tstamp + "," + msg; StreamWriter sw = new StreamWriter(logFile, true); sw.WriteLine(rmsg); sw.Flush(); sw.Close(); } } }

Add this to your forms onload event

LogProvider.Logging.LogDir = "C:\\Users\\Ece\\Documents\\Testings"; LogProvider.Logging.LogFile = LogProvider.Logging.RandomFileName();

Now adjust your button click event to be like the following:

DialogResult dia = MessageBox.Show("Wanna continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dia == DialogResult.Yes) { StringBuilder logMsg = new StringBuilder(); logMsg.Append("Name Surname:" + text1.Text + text2.Text + Environment.NewLine); logMsg.Append("Other:" + text3.Text + text4.Text + Environment.NewLine); logMsg.Append("Money:" + textBox1.Text + " TL." + Environment.NewLine); logMsg.Append("*************************************" + Environment.NewLine); LogProvider.Logging.AddLog(logMsg.ToString()); } else { return; }

Now you should only create one file for the entire time that application is running and will log to that one file every time you click your button.

更多推荐

本文发布于:2023-04-29 10:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336271.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日志   logs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!