1

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.

LCIII
  • 3,102
  • 3
  • 26
  • 43

3 Answers3

2

You could write the file with a different filename, then move it once you've populated it. According to this question, file moves are atomic within NTFS, so your service would never see a half-written file.

Community
  • 1
  • 1
adv12
  • 8,443
  • 2
  • 24
  • 48
2

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.

codingadventures
  • 2,924
  • 2
  • 19
  • 36
0

File.WriteAllText is what you're looking for. If the file does not exist, it will create it with the text in it on creation.

MaxOvrdrv
  • 1,780
  • 17
  • 32
  • 3
    The fact that it's provided as a single method in the framework doesn't guarantee that the implementation is atomic... – adv12 Feb 18 '15 at 18:41