如何使用SaveFileDialog将stringbuilder的内容保存到文本文件?

8 save winforms

这是一个winforms应用程序.

在Windows中,我希望用户单击并按钮,然后弹出窗口应该让用户选择他们想要保存文件的路径.

Jon*_*ant 31

你想要WriteAllText函数.

using (SaveFileDialog dialog = new SaveFileDialog()) {
    if (dialog.ShowDialog(this) == DialogResult.OK) {
        File.WriteAllText(dialog.FileName, yourStringBuilder.ToString());
    }
}
Run Code Online (Sandbox Code Playgroud)


sbe*_*kur 5

不再想...

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2 {
public partial class Form1 : Form {

    StringBuilder sb = new StringBuilder();

    public Form1() {
        InitializeComponent();

        sb.Append("This is going ");
        sb.Append("to be saved to a text file");
    }

    private void button1_Click(object sender, EventArgs e) {
        using (SaveFileDialog dlg = new SaveFileDialog()) {
            if (dlg.ShowDialog() == DialogResult.OK) {
                string fileName = dlg.FileName;
                SaveToFile(fileName);
            }
        }
    }

    private void SaveToFile(string fileName) {
        System.IO.TextWriter w = new System.IO.StreamWriter(fileName);
        w.Write(sb.ToString());
        w.Flush();
        w.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)


gim*_*mel 1

StringBuilder.ToString()TextStream.Write()可以在创建文件后传递给该方法。

使用SaveFileDialog 类,您可以让用户以标准方式选择路径和文件名。文档中的详细示例。