Reputation: 1092
Clicking on the the Get List
Button:
Clicking on the Create Folders
Button,
I want to remove the duplicate extensions and create folders named after the items in the ListBox.
i.e., create folders with names: doc
, docx
, dwg
etc.
private void btn_list_Click(object sender, EventArgs e)
{
listBox_ex.Items.Clear();
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
lbl_path.Text = FBD.SelectedPath;
listBox_name.Items.Clear();
string[] filename = Directory.GetFiles(FBD.SelectedPath);
foreach (string file in filename)
{
listBox_name.Items.Add(Path.GetFileName(file));
listBox_ex.Items.Add(Path.GetExtension(file).Replace(".", ""));
}
}
}
private void btn_CreateFolder_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD2 = new FolderBrowserDialog();
if (FBD2.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
lbl_pathCreated.Text = FBD2.SelectedPath;
}
string path = lbl_pathCreated.Text;
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
} else {
MessageBox.Show("already exit");
}
}
Upvotes: 0
Views: 367
Reputation: 32248
Alternative method, using 2 List<string>
objects to store the current files' selection and the files extensions as Distinct, Ordered elements.
The Lists are then used as the ListBox.DataSource.
A ListBox.Items
collecton is reset when the DataSource is changed.
When a destination Path is selected, each item in the List of extensions is used to create a Directory in the selected path.
No need to check whether the Directory already exists: Directory.CreateDirectory() just ignores it.
You might want to add a validation procedure for the Path a user seleted. The user may have picked a weird destination.
List<string> fileNames = null;
List<string> fileExtensions = null;
private void btn_list_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog fbd = new FolderBrowserDialog())
{
if (fbd.ShowDialog() == DialogResult.OK)
{
lbl_path.Text = fbd.SelectedPath;
fileNames = Directory.GetFiles(fbd.SelectedPath).ToList();
fileExtensions = fileNames.Select(item =>
Path.GetExtension(item).Replace(".", "")).Distinct().OrderBy(n => n).ToList();
listBox_name..DataSource = fileNames.Select(f => Path.GetFileName(f)).ToList();
listBox_ex.DataSource = fileExtensions;
}
}
}
private void btn_CreateFolder_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog fbd = new FolderBrowserDialog())
{
if (fbd.ShowDialog() == DialogResult.OK)
{
lbl_pathCreated.Text = fbd.SelectedPath;
fileExtensions.ForEach(item =>
Directory.CreateDirectory(Path.Combine(fbd.SelectedPath, item)));
}
}
}
Upvotes: 2