带有时间戳的txt文件名,使用DateTime.Now c#

时间:2015-10-08 03:45:25

标签: c# datetime

当我尝试学习C#时,我不断尝试新的东西,我认为这些东西可能与学习相关。这时我一直在尝试做一些简单的事情,比如使用streamwriter将List的内容写入txt文件,并使用DateTime.Now方法使文件名包含时间戳。然而,事实证明这比我想象的更难。这是我试图用于包含在streamwriter中的路径的代码:

using System;
using System.IO;
namespace Learning
{
    public class FileWriter
    {  
      string path = System.IO.Path.Combine(@"My text"+DateTime.Now.ToString("yy,mm,dd")+".txt");

    }
}
不用说,这种格式不被接受。

来自Java,我首先尝试了这段代码

public class FileWriter
{
    string time = DateTime.Now.ToString("yy,mm,dd");
    string path = System.IO.Path.Combine(@"My text"+time+".txt");
    Streamwriter sw = new Streamwriter(path,false);
}

只导致“字段初始化程序无法引用非静态字段方法或属性”错误。除非我错了,否则你可以用Java做到这一点。

我试图谷歌,发现了一些可能含糊地问同样事情的点击,虽然我根本不理解代码片段。

最后,我最终通过使用以下代码来解决问题:

string time = DateTime.Now.ToString("yy,mm,dd");
File.Copy("My text.txt","New text"+time+".txt");
File.Delete("My text.txt");

然而,我觉得这应该能够以更接近我原来想法的方式解决。

你们中的任何人能帮助我以更接近原始思路的方式解决我的问题吗? (更靠近第一个或第二个代码片段?)

2 个答案:

答案 0 :(得分:0)

试试这个:

    // Example #1: Write an array of strings to a file.
    // Create a string array that consists of three lines.
    string[] lines = { "First line", "Second line", "Third line" };
    // WriteAllLines creates a file, writes a collection of strings to the file,
    // and then closes the file.  You do NOT need to call Flush() or Close().
    System.IO.File.WriteAllLines(string.Format(@"C:\Users\Public\TestFolder\WriteLines{0}.txt",DateTime.Now.ToString("yy,mm,dd")), lines);

此处可以找到更多示例https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx

答案 1 :(得分:0)

string path = 
    System.IO.Path.Combine(@"My_Text" + DateTime.Now.ToString("yy-MM-dd") + ".txt");

string path = 
   System.IO.Path.Combine(@"My_Text" + DateTime.Now.ToString("yy_MM_dd") + ".txt");
相关问题