If your program needs to
insert text in a
closed file at a certain position, or at the beginning (prepend), you will need to rebuild the file to achieve that.
Your code doesn't appear to require inserting in an existing closed file.
Partly for reasons that Maciej described in his solution, I suggest you always use a StringBuilder: add
all the text; then, when complete, write the StringBuilder content to the file.
I think you can re-order the flow of user input in the Console so that you never have to insert within the file.
However, in case you must insert:
using System;
using System.IO;
using System.Text;
namespace YourNameSpace
{
public enum WriteWhere
{
Append, PrePend, InsertReplacingMarker, InsertPreservingMarker
}
public class SBWriter
{
public SBWriter(string fileName)
{
if (!File.Exists(fileName))
{
throw new FileNotFoundException(@"{FileName} invalid");
}
FileName = fileName;
}
StringBuilder sb = new StringBuilder();
private StreamWriter Writer;
private string FileName;
public void WriteToSB(string text, WriteWhere whereto = WriteWhere.Append, string marker = "")
{
switch(whereto)
{
case WriteWhere.Append:
sb.AppendLine(text);
break;
case WriteWhere.PrePend:
sb.Insert(0, text + Environment.NewLine);
break;
case WriteWhere.InsertReplacingMarker:
sb.Replace(marker + Environment.NewLine, text + Environment.NewLine);
break;
case WriteWhere.InsertPreservingMarker:
sb.Replace(marker, string.Format("{0}{1}", marker + Environment.NewLine, text));
break;
default:
throw new ArgumentOutOfRangeException(nameof(whereto), whereto, null);
}
}
public void WriteFile()
{
File.WriteAllText(FileName, sb.ToString());
}
}
}
Sample usage:
SBWriter sbw = new SBWriter(@"C:\Users\test_user\Desktop\Test\test.txt");
sbw.WriteToSB("hello");
sbw.WriteToSB("xxx");
sbw.WriteToSB("qwr");
sbw.WriteToSB("sffsfqf");
sbw.WriteToSB("beginning", WriteWhere.PrePend);
sbw.WriteToSB("zzzz");
sbw.WriteToSB("yyyyy");
sbw.WriteToSB(@"yo mama", WriteWhere.InsertReplacingMarker, "xxx");
Note that the StringBuilder 'Replace function will replace
all instances of its target string.