如何保存C#中的日志?

Lad*_*our 0 c# logging

这是一个用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;
        }


    }
Run Code Online (Sandbox Code Playgroud)

rah*_*hul 6

您可以附加到文件中的文本.

看到

File.AppendText

using (StreamWriter sw = File.AppendText(pathofFile)) 
        {
            sw.WriteLine("This");
            sw.WriteLine("is Extra");
            sw.WriteLine("Text");
        }
Run Code Online (Sandbox Code Playgroud)

其中pathofFile是要附加到的文件的路径.