C# winform中 选择文件和保存文件

转载自https://blog.csdn.net/qq_31788297/article/details/62047952

我们在使用桌面软件的时候经常会使用到选择文件并打开和另存为等的窗口,这样方便了我们自由选择打开文件和保存文件的路径。 
注:下面说的这两个功能,只是返回文件路径。具体打开和保存功能还需要结合C#的IO流。 
话不多说,先写两段代码让你体验一下效果,具体的对象有哪些功能,可以单独查一查相应的函数。

**

选择文件功能

** 
你可以创建一个button按钮,把代码直接放到按钮的点击事件中,当点击按钮后就会弹出文件选择窗口

       private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = "所有文件(*xls*)|*.xls*"; //设置要选择的文件的类型
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                string file = fileDialog.FileName;//返回文件的完整路径                
            }
        }       

文件选择窗口

文件保存路径选择功能

下面是文件保存路径的选择,最终会返回一个完整的路径

  //选择保存路径
        private string ShowSaveFileDialog()
        {
            string localFilePath = "";
            //string localFilePath, fileNameExt, newFileName, FilePath; 
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "Excel表格(*.xls)|*.xls";

            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;

            //点了保存按钮进入 
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                localFilePath = sfd.FileName.ToString(); //获得文件路径 
                string fileNameExt =localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1); //获取文件名,不带路径

                //获取文件路径,不带文件名 
                //FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\")); 

                //给文件名前加上时间 
                //newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt; 

                //在文件名里加字符 
                //saveFileDialog1.FileName.Insert(1,"dameng"); 

                //System.IO.FileStream fs = (System.IO.FileStream)sfd.OpenFile();//输出文件 

                ////fs输出带文字或图片的文件,就看需求了 
            }

            return localFilePath;
        }

猜你喜欢

转载自www.cnblogs.com/luxishi/p/9253021.html