How to write to the beginning of a file using Stream Writer?

I want to insert my line at the beginning of the file. But there is no function to add to the beginning in the stream writer. So how do I do this?

My code is:

string path = Directory.GetCurrentDirectory() + "\\test.txt"; StreamReader sreader = new StreamReader(path); string str = sreader.ReadToEnd(); sreader.Close(); StreamWriter swriter = new StreamWriter(path, false); swriter.WriteLine("example text"); swriter.WriteLine(str); swriter.Close(); 

But this does not seem optimized. So is there any other way?

+6
source share
3 answers

You are almost there:

  string path = Directory.GetCurrentDirectory() + "\\test.txt"; string str; using (StreamReader sreader = new StreamReader(path)) { str = sreader.ReadToEnd(); } File.Delete(path); using (StreamWriter swriter = new StreamWriter(path, false)) { str = "example text" + Environment.NewLine + str; swriter.Write(str); } 
+8
source

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); } 
+4
source

Something like that:

  private void WriteToFile(FileInfo pFile, string pData) { var fileCopy = pFile.CopyTo(Path.GetTempFileName(), true); using (var tempFile = new StreamReader(fileCopy.OpenRead())) using (var originalFile = new StreamWriter(File.Open(pFile.FullName, FileMode.Create))) { originalFile.Write(pData); originalFile.Write(tempFile.ReadToEnd()); originalFile.Flush(); } fileCopy.Delete(); } 
0
source

Source: https://habr.com/ru/post/924924/


All Articles