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.
To call:
Note a few things:
To answer the question in your comment on @Scott Ivey's answer: to specify where the file is written to, prepend the desired path to the file name before or in the call to CreateText().
For example:
or
Try this:
?
You'd want to do a custom string format on DateTime.Now. You can use String.Format() to combine the results of that with your base filename.
To append on the path to the filename, use Path.Combine().
Finally, use a using() block to properly close & dispose your StreamWriter when you are finished with it...
Edit: fixed sample to account for path of "C:\Documents and Settings\bob.jones\Desktop"