保存文件对话框 SaveFileDialog所完成的工作是让用户指定存放文件的路径和文件类型,实际的保存工作需要用文件流操作完成。示例代码如下:
(1)在Visual Studio中创建一个“Windows窗体应用程序”
(2)在Form1上布置一个TextBox和一个Button,并将textBox1的Multiline属性设置为true,允许textBox1多行输入

(3)窗体代码Form1.cs
using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Text = "保存";
// 允许textBox1多行输入
textBox1.Multiline = true;
}
private void button1_Click(object sender, EventArgs e)
{
// "保存为"对话框
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "文本文件|*.txt";
// 显示对话框
if (dialog.ShowDialog() == DialogResult.OK)
{
// 文件名
string fileName = dialog.FileName;
// 创建文件,准备写入
FileStream fs = File.Open(fileName,
FileMode.Create,
FileAccess.Write);
StreamWriter wr = new StreamWriter(fs);
// 逐行将textBox1的内容写入到文件中
foreach (string line in textBox1.Lines)
{
wr.WriteLine(line);
}
// 关闭文件
wr.Flush();
wr.Close();
fs.Close();
}
}
}
}