简体   繁体   中英

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

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:

  • 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);

?

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);

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