创建一个新的.txt文件,日期在前面,C# [英] Creating a new .txt file with date in front, C#
本文介绍了创建一个新的.txt文件,日期在前面,C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图得到以下内容:[今天的日期] ___ [textfilename] .txt从以下代码:
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");
}
}
}
我尝试放入 DateTime.Now.ToString()
,但我不能组合字符串。任何人都可以帮助我吗?
I tried putting in DateTime.Now.ToString()
but i cannot combine the strings.
我想要在FRONT创建新文本文件标题的日期。
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");
}
}
致电:
WriteToFile(@"C:\mydirectory", "myfilename");
请注意以下几点:
- 使用自定义格式字符串指定日期,并避免在NTFS中使用字符非法。
- 前缀包含带有@字符串文字标记的路径的字符串,因此您可以
- 将路径部分与Path.Combine()相结合,避免使用路径分隔符。
- 在创建StreamWriter时使用使用块;退出该块将处理
StreamWriter,并自动关闭该文件。
- 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.
这篇关于创建一个新的.txt文件,日期在前面,C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文