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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/941132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:50:52  来源:igfitidea点击:

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

c#datetimetext-files

提问by yeahumok

I am trying to get the following: [today's date]___[textfilename].txt from the following code:

我试图从以下代码中获取以下内容:[今天的日期]___[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");



        }
    }
}

I tried putting in DateTime.Now.ToString()but i cannot combine the strings.

我尝试放入,DateTime.Now.ToString()但我无法组合字符串。

Can anybody help me? I want the date in FRONT of the title of the new text file I am creating.

有谁能够帮助我?我想要我正在创建的新文本文件的标题前面的日期。

采纳答案by Michael Petrotta

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.
  • 使用自定义格式字符串指定日期,并避免使用 NTFS 中的非法字符。
  • 包含带有“@”字符串文字标记的路径的前缀字符串,因此您不必转义路径中的反斜杠。
  • 使用 Path.Combine() 组合路径部分,并避免使用路径分隔符。
  • 创建 StreamWriter 时使用 using 块;退出块将处置 StreamWriter,并自动为您关闭文件。

回答by Scott Ivey

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.

您想在 DateTime.Now 上执行自定义字符串格式。您可以使用 String.Format() 将结果与您的基本文件名结合起来。

To append on the path to the filename, use Path.Combine().

要将路径附加到文件名,请使用 Path.Combine()。

Finally, use a using() block to properly close & dispose your StreamWriter when you are finished with it...

最后,使用 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");

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

编辑:固定示例以说明“C:\Documents and Settings\bob.jones\Desktop”的路径

回答by Andy Mikula

Try this:

尝试这个:

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

?

?

回答by 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().

要回答您对@Scott Ivey 的回答的评论中的问题:要指定文件的写入位置,请在调用 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);