简体   繁体   中英

txt filename with a timestamp using DateTime.Now c#

As I try to learn C# i am constantly trying new things that i feel could be relevant to learn. At this time i have been trying to do something as simple as writing the contents of a List to a txt file using the streamwriter and having the file name include a timestamp using the DateTime.Now method. However, this proved harder than i first thought. Here is the code i tried to use for the path to include in 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");

    }
}

needless to say, this format was not accepted.

Having come from Java, i first tried this code

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

which only resulted in a "a field initializer cannot reference the nonstatic field method or property" error. Unless im mistaken, you are allowed to do this in Java.

I tried to google, found a couple of hits that might have vaguely asked about the same thing, although i didnt understand the codesnippets at all.

In the end, i ended up sovling the problem by using the following code:

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

However, i feel that this should be able to be solved in a manner more close to my original idea.

Can any of you help me to solve my problem in a manner closer to my original train of thought? (closer to the first or second code snippet?)

Try this:

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

More examples can be found here https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM