简体   繁体   中英

Write text filename as date in c#

So I've looked around for the answer and I'm just getting started with using c# so its probably simple, but I've got a block of code

private void btnAdd_Click(object sender, EventArgs e)
{
    using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "TextDocuments|*.txt", ValidateNames = true })
    {
        if (sfd.ShowDialog() == DialogResult.OK)
        {

            using (StreamWriter sw = new StreamWriter(sfd.FileName))
            {
                sw.WriteLineAsync(txtMessage.Text);
                MessageBox.Show("Your entry has been saved successfully!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }       
}

What I want to know is how I'm meant to preset the filename as a date in this code?

assign the current DateTime to DefaultFileName property on save file dialog instance

sfd.DefaultFileName=DateTime.Now.ToString();

or

sfd.FileName=DateTime.Now.ToString();
    string logPath = string.Format("{0:yyyy-MM-dd}.txt", DateTime.Now); 
        Console.WriteLine("Path: " + logPath);

            using (StreamWriter file = new StreamWriter(@"./" + logPath, true))
            {
                file.Write(string.Format("{0} {1} {2} {3}", DateTime.Now, log, Environment.NewLine, bankLog));
            }
            Console.WriteLine("Logs inserted to file");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM