c#中如何用SaveFileDialog把TextBox的值保存到指定的txt文件中?_百度知...

发布网友 发布时间:2024-10-24 16:11

我来回答

3个回答

热心网友 时间:2024-11-17 04:52

保存文件对话框 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();
            }
        }
    }
}

热心网友 时间:2024-11-17 04:44

我建议你用xml序列化实现,不要自己控制着往文本里写,那样的话读取和扩展都会不方便,特别是将来你面对版本升级的时候更麻烦!
比如你这个可以将上面的信息建立一个类 People,然后维护一个List<People> 对象,再去序列化这个对象,这样就很容易操作了。

热心网友 时间:2024-11-17 04:45

if(savefiledialog.showdialog==resultdialog.ok)
{
savefiledialog.fileter="*.txt|*.txt";//保存为txt文件
string fname=savefiledialog.filename;//要保存的文件
streamwrter sw=new streamwriter(fname);
sw.write(textbox的内容);
sw.close();
}
这样就可以了

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com