我想从以下代码中获取以下内容:[今天的日期] ___ [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");
}
}
}
我尝试输入DateTime.Now.ToString()
,但我无法合并字符串。
任何人都可以帮助我吗?我希望FRONT中的日期是我正在创建的新文本文件的标题。
答案 0 :(得分:20)
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");
请注意以下几点:
答案 1 :(得分:12)
您想在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”的路径
答案 2 :(得分:1)
试试这个:
string fileTitle = "testtext.txt";
string fileDirectory = "C:\\Documents and Settings\username\My Documents\";
File.CreateText(fileDirectory + DateTime.Now.ToString("ddMMYYYY") + fileTitle);
答案 3 :(得分:0)
要回答您对@Scott Ivey's answer的评论中的问题: 指定文件的写入位置,在调用CreateText()之前或之中,在文件名前面添加所需的路径。
例如:
String path = new String (@"C:\Documents and Settings\bob.jones\Desktop\");
StreamWriter sw = File.CreateText(path + myFileName);
或
String fullFilePath = new String (@"C:\Documents and Settings\bob.jones\Desktop\");
fullFilePath += myFileName;
StreamWriter sw = File.CreateText(fullFilePath);