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

I am trying to get the following: [today 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 to insert DateTime.Now.ToString(), but I can not concatenate the lines.

Can someone help me? I need the date in FRONT of the name of the new text file that I am creating.

+3
source share
4 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");

Pay attention to a few things:

  • Specify the date using a custom format string and do not use characters that are illegal in NTFS.
  • Prefix lines containing paths with the literal marker of the string "@", so you do not need to hide the backslash in the path.
  • Path.Combine() .
  • StreamWriter; StreamWriter .
+20

DateTime.Now. String.Format(), .

, Path.Combine().

, using(), StreamWriter, ...

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

: "C:\Documents and Settings\bob.jones\Desktop"

+12

:

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

?

+1

To answer the question in your comment @Scott Ivey answer : to indicate where to save the file, add the desired path to the file name before or in the CreateText () call.

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

Source: https://habr.com/ru/post/1709618/


All Articles