Search code examples
c#stringbuildersavefiledialog

Appending filename of savedialog to the file which is going to be saved


I am trying to append the name of file in the first line of my text file which is going to be saved. How can I do it? Here is a the code. I couldn't find a method for stringbuilder to append at the beginning of its instance.

StringBuilder sb = new StringBuilder();

sb.AppendLine("BLAH BLAH");

if (saveFile.ShowDialog() == DialogResult.OK)
{
   //How to append file name at the beggining of the file to be saved?

    File.WriteAllText(saveFile.FileName, sb.ToString());
}

Solution

  • Add this line before you call WriteAllText:

    sb.Insert(0, saveFile.FileName + Environment.NewLine);
    

    -- or --

    string outString = saveFile.FileName + Environment.NewLine + sb.ToString();  
    File.WriteAllText(saveFile.FileName, outString);