Vivek Agrawal
Vivek Agrawal

Reputation: 113

Performance wise: File.Copy vs File.WriteAllText function in C#?

I have file content in string and I need to put the same content in 3 different files. So, I am using File.WriteAllText() function of C# to put the content in first file. now, for other 2 files, I have two options:

  1. Using File.Copy(firstFile, otherFile)
  2. Using File.WriteAllText(otherFile, content)

Performance wise which option is better?

Upvotes: 2

Views: 895

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109537

If the file is relatively small it is likely to remain cached in Windows disk cache, so the performance difference will be small, or it might even be that File.Copy() is faster (since Windows will know that the data is the same, and File.Copy() calls a Windows API that is extremely optimised).

If you really care, you should instrument it and time things, although the timings are likely to be completely skewed because of Windows file caching.

One thing that might be important to you though: If you use File.Copy() the file attributes including Creation Time will be copied. If you programatically create all the files, the Creation Time is likely to be different between the files.

If this is important to you, you might want to programatically set the the file attributes after the copy so that they are the same for all files.

Personally, I'd use File.Copy().

Upvotes: 4

Related Questions