I am trying to get the following: [today's date]___[textfilename].txt from the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication29
{
class Program
{
static void Main(string[] args)
{
WriteToFile();
}
static void WriteToFile()
{
StreamWriter sw;
sw = File.CreateText("c:\\testtext.txt");
sw.WriteLine("this is just a test");
sw.Close();
Console.WriteLine("File created successfully");
}
}
}
I tried putting in DateTime.Now.ToString()
but i cannot combine the strings.
Can anybody help me? I want the date in FRONT of the title of the new text file I am creating.
static void WriteToFile(string directory, string name)
{
string filename = String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now, name);
string path = Path.Combine(directory, filename);
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("This is just a test");
}
}
To call:
WriteToFile(@"C:\mydirectory", "myfilename");
Note a few things:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With