關於OpenFileDialog的使用

 

 

爲了方便同事在日常工作中很快速生成大量數據, 我做了文件拷貝的小工具:

其中用到了OpenFileDialog這個類,下面是關於這個類的一些用法!

OpenFileDialog類是用來選擇文件位置的,

FolderBrowserDialog 類用來選擇文件夾位置.

具體代碼如下:

程序源碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace copyFile
{
    public partial class Form1 : Form
    {
        String fileName;
        String folderName;
        String extendedName;
        String fileName1;
       
        public Form1()
        {
            InitializeComponent();
        }

        private void browse_Click(object sender,EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();                //new一個方法
            ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); //定義打開的默認文件夾位置
            ofd.ShowDialog();          //顯示打開文件的窗口
             fileName = ofd.FileName;                //獲得選擇的文件路徑
             textBox1.Text = fileName;
             extendedName = Path.GetExtension(fileName);       //獲得文件擴展名
             fileName1 = Path.GetFileName(fileName);           //獲得文件名
        }

        private void folder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowDialog();
            folderName = fbd.SelectedPath;                     //獲得選擇的文件夾路徑
            textBox3.Text = folderName;
        }

        private void ok_Click(object sender, EventArgs e)
        {
             if (textBox1.Text.Trim().Length == 0)
            {
                MessageBox.Show("文件路徑不能爲空!");
                return;
            }
            if (textBox2.Text.Trim().Length == 0)
            {
                MessageBox.Show("複製數量不能爲空!");
                return;
            }
            if (textBox3.Text.Trim().Length == 0)
            {
                MessageBox.Show("目標文件夾路徑不能爲空!");
                return;
            }
            String newFile;                   //定義存儲的位置,和存儲的名稱
           
            for (int i = 1; i <= Convert.ToInt32(textBox2.Text); i++)                   //從textBox2中獲取要複製的次數
            {
                newFile = folderName + "\\" + fileName1 +"_"+ i.ToString() + extendedName;

;       File.Copy(fileName, newFile, true);            //使用Copy複製文件, Copy(源文件位置,目標文件夾位置,是否可以覆蓋同名文件)
            }
            MessageBox.Show("複製完成!");
        }
    }
}

 

補充:

//獲取文件名
Path.GetFileName(OpenFileDialog.FileName)

//
獲取文件路徑
Path.GetDirectoryName(OpenFileDialog.FileName)

//
獲取文件擴展名
Path.GetExtension(OpenFileDialog.FileName)

 

 

 

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章