开发者

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

开发者 https://www.devze.com 2023-03-04 19:32 出处:网络
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 b

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());
}
0

精彩评论

暂无评论...
验证码 换一张
取 消