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 begi开发者_如何学运维nning 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());
}
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);
To keep previous text:
StringBuilder sb = new StringBuilder();
// Appending string to your StringBuilder string value.
sb.AppendLine("BLAH BLAH");
if (saveFile.ShowDialog() == DialogResult.OK)
{
// Keep the previous file text .. By inserting it in the begining of the
// StringBuilder string value.
sb.Insert(0, File.ReadAllText(saveFile.FileName) + Environment.NewLine);
// Insert File Name in the begining of the StringBuilder string value.
sb.Insert(0, saveFile.FileName + Environment.NewLine);
File.WriteAllText(saveFile.FileName, sb.ToString());
}
精彩评论