For OpenFileDialog:
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
{
string sFileName = choofdlog.FileName;
string[] arrAllFiles = choofdlog.FileNames; //used when Multiselect = true
}
For FolderBrowserDialog:
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Custom Description";
if (fbd.ShowDialog() == DialogResult.OK)
{
string sSelectedPath = fbd.SelectedPath;
}
To access selected folder
and selected file name
you can declare both string at class level.
namespace filereplacer
{
public partial class Form1 : Form
{
string sSelectedFile;
string sSelectedFolder;
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
//fbd.Description = "Custom Description"; //not mandatory
if (fbd.ShowDialog() == DialogResult.OK)
sSelectedFolder = fbd.SelectedPath;
else
sSelectedFolder = string.Empty;
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
sSelectedFile = choofdlog.FileName;
else
sSelectedFile = string.Empty;
}
private void replacebtn_Click(object sender, EventArgs e)
{
if(sSelectedFolder != string.Empty && sSelectedFile != string.Empty)
{
//use selected folder path and file path
}
}
....
}
NOTE:
As you have kept choofdlog.Multiselect=true;
, that means in the OpenFileDialog()
you are able to select multiple files (by pressing ctrl
key and left mouse click for selection).
In that case you could get all selected files in string[]
:
At Class Level:
string[] arrAllFiles;
Locate this line (when Multiselect=true
this line gives first file only):
sSelectedFile = choofdlog.FileName;
To get all files use this:
arrAllFiles = choofdlog.FileNames; //this line gives array of all selected files
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…