Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 333
yeahumok Avatar asked Nov 27 '22 02:11

yeahumok


1 Answers

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.
like image 182
Michael Petrotta Avatar answered Nov 29 '22 15:11

Michael Petrotta