Search code examples
c#.net-4.5filestream

How do I create an already populated text file?


I want to create a text file with the extension .jrq and populate it with two lines. However I want this to happen "all at once" instead of creating the text file and then adding the two lines. Basically I need to create an already populated text file.

Here is my current code:

FileStream fileStream = new FileStream(folder + filename + ".jrq", FileMode.Create);
StreamWriter streamWriter = new StreamWriter(fileStream);

streamWriter.WriteLine("Line1");
streamWriter.WriteLine("Line2");

streamWriter.Flush();
streamWriter.Close();

The reason I need the file creation and the file appending to happen together is because I have a windows service that scans the folder that this text file will be created in and that service triggers a job the second it sees a .jrq file (and does logic based on what's written in the file). It notices the .jrq file before I've written anything in it and throws an error.


Solution

  • I think you are better off using a small trick. As adv12 pointed out writing all at once with one single method does not guarantee the implementation is atomic. if I were you I would create a temporary file:

    FileStream fileStream = new FileStream(folder + filename + ".tmp", 
    
    FileMode.Create);
    StreamWriter streamWriter = new StreamWriter(fileStream);
    
    streamWriter.WriteLine("Line1");
    streamWriter.WriteLine("Line2");
    
    streamWriter.Flush();
    streamWriter.Close();
    

    and then rename it using File.Move:

    System.IO.File.Move(folder + filename + ".tmp",folder + filename + ".jrq");
    

    So the job will start when the file jrq is full of data. it's not a super elegant solution but it would work.

    Hope it helps.