将 savedialog 的文件名附加到要保存的文件中

发布于 2024-11-06 00:16:06 字数 348 浏览 3 评论 0原文

我试图将文件名附加到要保存的文本文件的第一行中。我该怎么做呢?这是代码。我找不到 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());
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不必你懂 2024-11-13 00:16:06

在调用 WriteAllText 之前添加此行:

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

-- 或 --

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

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);
北城半夏 2024-11-13 00:16:06

要保留以前的文本:

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

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());
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文