将保存对话框的文件名附加到要保存的文件中

时间:2011-05-11 00:14:12

标签: c# stringbuilder savefiledialog

我正在尝试将文件名附加到我要保存的文本文件的第一行。我该怎么做?这是一个代码。我找不到一个stringbuilder的方法,可以在其实例的开始处附加。

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

感谢。

2 个答案:

答案 0 :(得分:2)

在调用WriteAllText之前添加此行:

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

- 或 -

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

答案 1 :(得分:1)

保留以前的文字:

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