Creating a new .txt file with date in front, C#

ぐ巨炮叔叔 提交于 2019-12-04 13:14:24
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:

  • Specify the date with a custom format string, and avoid using characters illegal in NTFS.
  • Prefix strings containing paths with the '@' string literal marker, so you don''t have to escape the backslashes in the path.
  • Combine path parts with Path.Combine(), and avoid mucking around with path separators.
  • Use a using block when creating the StreamWriter; exiting the block will dispose the StreamWriter, and close the file for you automatically.

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...

string myFileName = String.Format("{0}__{1}", DateTime.Now.ToString("yyyyMMddhhnnss"), "MyFileName");
strign myFullPath = Path.Combine("C:\\Documents and Settings\\bob.jones\\Desktop", myFileName)
using (StreamWriter sw = File.CreateText(myFullPath))
{
    sw.WriteLine("this is just a test");
}

Console.WriteLine("File created successfully");

Edit: fixed sample to account for path of "C:\Documents and Settings\bob.jones\Desktop"

Try this:

string fileTitle = "testtext.txt";
string fileDirectory = "C:\\Documents and Settings\username\My Documents\";
File.CreateText(fileDirectory + DateTime.Now.ToString("ddMMYYYY") + fileTitle);

?

JeffH

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:

String path = new String (@"C:\Documents and Settings\bob.jones\Desktop\");
StreamWriter sw = File.CreateText(path + myFileName);

or

String fullFilePath = new String (@"C:\Documents and Settings\bob.jones\Desktop\");
fullFilePath += myFileName;
StreamWriter sw = File.CreateText(fullFilePath);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!