创建一个前面有日期的新.txt文件,C#

yea*_*mok 4 c# datetime text-files

我试图从以下代码获得以下内容:[今天的日期] ___ [textfilename] .txt:

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



        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我试过投入,DateTime.Now.ToString()但我无法组合字符串.

有谁能够帮我?我希望FRONT中的日期是我正在创建的新文本文件的标题.

Mic*_*tta 21

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

致电:

WriteToFile(@"C:\mydirectory", "myfilename");
Run Code Online (Sandbox Code Playgroud)

请注意以下几点:

  • 使用自定义格式字符串指定日期,并避免在NTFS中使用非法字符.
  • 包含带有'@'字符串文字标记的路径的前缀字符串,因此您不必转义路径中的反斜杠.
  • 使用Path.Combine()组合路径部分,并避免使用路径分隔符进行混乱.
  • 创建StreamWriter时使用using块; 退出该块将释放StreamWriter,并自动为您关闭该文件.


Sco*_*vey 13

您想在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");
Run Code Online (Sandbox Code Playgroud)

编辑:修复示例以考虑"C:\ Documents and Settings\bob.jones\Desktop"的路径