c#保存自定义文件名和路径的txt用法

如图代码是,点击按钮,把接收到的数据保存在D盘test.txt文件夹里面
现在我想的是:点击按钮,跳出一个对话框,自定义文件名和路径,点击
保存,保存到我选择的路径和输入的文件名!!请教如何改下代码!!!!!!

利用SaveFileDialog,让用户自己指定要保存文本文件的路径。实现方法如下

(1)在Visual Studio中新建一个“Windows 窗体应用程序”项目

(2)在Form1上布置一个TextBox控件和一个Button控件。textBox1属性设置如下

    Multiline = true

    ScrollBars = both

(3)Form1窗体代码Form1.cs

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;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            button1.Text = "保存到文件...";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 利用SaveFileDialog,让用户指定文件的路径名
            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.Filter = "文本文件|*.txt";
            if (saveDlg.ShowDialog() == DialogResult.OK)
            {
                // 创建文件,将textBox1中的内容保存到文件中
                // saveDlg.FileName 是用户指定的文件路径
                FileStream fs = File.Open(saveDlg.FileName, 
                    FileMode.Create, 
                    FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                
                // 保存textBox1中所有内容(所有行)
                foreach (string line in textBox1.Lines)
                {
                    sw.WriteLine(line);
                }
                //关闭文件
                sw.Flush();
                sw.Close();
                fs.Close();
                // 提示用户:文件保存的位置和文件名
                MessageBox.Show("文件已成功保存到" + saveDlg.FileName);
            }
        }
    }
}

(4)运行效果

点击“保存到文件...”按钮后的对话框,用户可以指定保存文件的位置和文件名

保存成功后的提示

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-04-13
private void button2_Click(object sender, EventArgs e)
{
using(SaveFileDialog sfd = new SaveFileDialog())
{
sfd.Filter = "Data Files(*.TXT)|*.txt";
if(sfd.ShowDialog(this) == DialogResult.OK)
{
axCipher781.bIR = true;
axCipher781.ConnectString = "115200";
axCipher781.Port = 1;
axCipher781.Connect();
axCipher781.ReadFile(sfd.FileName);
}
}
}

本回答被提问者采纳
相似回答