If you do not need to consider that other processes are written to the same file, and your process has permissions to create a directory, the most effective way to deal with it would be:
- create a new file called temp
- write new text
- add old text from your file
- delete a file
- rename temporary file
it will not be so cool and fast, but at least you wonβt have to allocate a huge line in memory for the approach you are using now.
however, if you are sure that the files will be small, for example, less than a few megabytes, your approach is not so bad.
however, you could simplify your code a bit:
public static void InsertText( string path, string newText ) { if (File.Exists(path)) { string oldText = File.ReadAllText(path); using (var sw = new StreamWriter(path, false)) { sw.WriteLine(newText); sw.WriteLine(oldText); } } else File.WriteAllText(path,newText); }
and for large files (i.e.> several MB)
public static void InsertLarge( string path, string newText ) { if(!File.Exists(path)) { File.WriteAllText(path,newText); return; } var pathDir = Path.GetDirectoryName(path); var tempPath = Path.Combine(pathDir, Guid.NewGuid().ToString("N")); using (var stream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None, 4 * 1024 * 1024)) { using (var sw = new StreamWriter(stream)) { sw.WriteLine(newText); sw.Flush(); using (var old = File.OpenRead(path)) old.CopyTo(sw.BaseStream); } } File.Delete(path); File.Move(tempPath,path); }
source share