winform控件事件_Winform控件SaveFileDialog用于保存文件

更新时间:2021-07-11    来源:WinForm    手机版     字体:

【www.bbyears.com--WinForm】

SaveFileDialog用于保存文件,供大家参考,具体内容如下

1、新建Winform窗体应用程序,命名为SaveFileDialogDemo。

2、在界面上添加一个按钮的控件(用于打开保存文件对话框),添加文本控件,用于输入要保存的内容。

3、后台代码实现:

 

 代码如下

usingSystem;

usingSystem.Collections.Generic;

usingSystem.ComponentModel;

usingSystem.Data;

usingSystem.Drawing;

usingSystem.IO;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Threading.Tasks;

usingSystem.Windows.Forms;

 

namespaceSaveFileDialogDemo

{

  publicpartialclassForm1 : Form

  {

    publicForm1()

    {

      InitializeComponent();

    }

 

    ///

    /// 保存文件按钮

    ///

    ///

    ///

    privatevoidbtn_SaveFile_Click(objectsender, EventArgs e)

    {

      //

      SaveFileDialog sfd =newSaveFileDialog();

      //设置保存文件对话框的标题

      sfd.Title ="请选择要保存的文件路径";

      //初始化保存目录,默认exe文件目录

      sfd.InitialDirectory = Application.StartupPath;

      //设置保存文件的类型

      sfd.Filter ="文本文件|*.txt|音频文件|*.wav|图片文件|*.jpg|所有文件|*.*";

      if(sfd.ShowDialog() == DialogResult.OK)

      {

        //获得保存文件的路径

        stringfilePath = sfd.FileName;

        //保存

        using(FileStream fsWrite =newFileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))

        {

          byte[] buffer = Encoding.Default.GetBytes(txt_FileInfo.Text.ToString().Trim());

          fsWrite.Write(buffer, 0, buffer.Length);

        }

      }

    }

  }

}

 

4、运行exe程序,在文本框中输入要保存的内容:

5、点击“保存文件”按钮,打开保存文件对话框,输入文件名,点击保存:

6、在Debug目录下面可以看到保存对话框.txt这个文件,打开文件,可以看到保存的内容:

本文来源:http://www.bbyears.com/asp/129013.html