Avatar of mrcoulson
mrcoulsonFlag for United States of America

asked on 

How can I use a variable from an folderBrowserDialog to make a string to create a directory?

Nice title, right?  Anyway, I'm doing this little app that creates directories.  I'm pretty happy with its operation thus far.  I have been specifying the initial path in which to create directories in the code:

string dir = @"C:\"

What I'd rather do is specify that dynamically from the results of a folderBrowserDialog.  I have the dialog box there and attached via a click event to a button.  I get the selected path into a string and use it to make the text of a label.

What I have not been able to do is replace C:\ with the string from folderBrowserDialog1.SelectedPath.ToString().

Help!


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
 
 
namespace directory_creator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        // Sets initial path for creating directories.  Declared globally (I think) because it needs to be referenced elsewhere.
        string strInitialPath;
 
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                strInitialPath = folderBrowserDialog1.SelectedPath.ToString();
                lblInitialPath.Visible = true;
                lblInitialPath.Text = "Creating directories in: " + strInitialPath + ".";
            }
        }
 
        private void button1_Click_1(object sender, EventArgs e)
        {
            string[] directoryNames = new string[15] { textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text, textBox6.Text, textBox7.Text, textBox8.Text, textBox9.Text, textBox10.Text, textBox11.Text, textBox12.Text, textBox13.Text, textBox14.Text, textBox15.Text };
 
            // Creates directories using strings built from the above array.
            foreach (string str in directoryNames)
            {
                string dir = @"C:\" + str;
                if ((str.Contains(@"\")) | (str.Contains("=")) | (str.Contains("*")) | (str.Contains("<")) | (str.Contains(">")) | (str.Contains("[")) | (str.Contains("]")) | (str.Contains("+")) | (str.Contains("/")) | (str.Contains(",")) | (str.Contains(".")) | (str.Contains(":")) | (str.Contains(";")))
                {
                    MessageBox.Show("The directory name " + dir + " contains invalid characters.");
                }
                else
                {
                    // Thanks to jcoehoorn for reminding me that Directory.Exists can't infer C:\!
                    if ((dir != @"C:\"))
                    {
                        if ((Directory.Exists(dir)))
                        {
                            MessageBox.Show("The directory " + str + " already exists!");
                        }
                        else
                        {
                            Directory.CreateDirectory(dir);
                        }
                    }
                }
             }
 
            // Clears the text boxes.
            foreach (Control cont in this.Controls)
            {
                if (cont is TextBox)
                {
                    ((TextBox)cont).Text = string.Empty;
                }
            }
 
        }
 
        private void btnClear_Click(object sender, EventArgs e)
        {
            // Clears the text boxes.
            foreach (Control cont in this.Controls)
            {
                if (cont is TextBox)
                {
                    ((TextBox)cont).Text = string.Empty;
                }
            }
        }
 
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox1 myNewForm = new AboutBox1();
            myNewForm.ShowDialog();
        }
 
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
 
    }
}

Open in new window

.NET ProgrammingC#

Avatar of undefined
Last Comment
mrcoulson
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

so, do you have an error message?
Avatar of mrcoulson
mrcoulson
Flag of United States of America image

ASKER

Sure!  It creates the directories, but I get a bunch of the messages like the one attached when I leave a few textboxes blank on the form.  It's supposed to skip them if they're blank.  I was having this problem before and then solved it; however, now that I've introduced this variable instead of hard-coding the path, it's back and I'm not sure why.  Is it because the @ is no longer there?  But if so, how would I add it?

I attached new code to reflect my changes.

Thanks!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
 
 
namespace directory_creator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        // Sets initial path for creating directories.  Declared globally (I think) because it needs to be referenced elsewhere.
        string strInitialPath;
 
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                strInitialPath = folderBrowserDialog1.SelectedPath.ToString();
                lblInitialPath.Visible = true;
                lblInitialPath.Text = "Creating directories in: " + strInitialPath + ".";
            }
        }
 
        private void button1_Click_1(object sender, EventArgs e)
        {
            string[] directoryNames = new string[15] { textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text, textBox6.Text, textBox7.Text, textBox8.Text, textBox9.Text, textBox10.Text, textBox11.Text, textBox12.Text, textBox13.Text, textBox14.Text, textBox15.Text };
 
            // Creates directories using strings built from the above array.
            foreach (string str in directoryNames)
            {
                string dir = strInitialPath + @"\" + str;
                if ((str.Contains(@"\")) | (str.Contains("=")) | (str.Contains("*")) | (str.Contains("<")) | (str.Contains(">")) | (str.Contains("[")) | (str.Contains("]")) | (str.Contains("+")) | (str.Contains("/")) | (str.Contains(",")) | (str.Contains(".")) | (str.Contains(":")) | (str.Contains(";")))
                {
                    MessageBox.Show("The directory name " + dir + " contains invalid characters.");
                }
                else
                {
                    // Thanks to jcoehoorn for reminding me that Directory.Exists can't infer C:\!
                    if ((dir != strInitialPath))
                    {
                        if ((Directory.Exists(dir)))
                        {
                            MessageBox.Show("The directory " + str + " already exists!");
                        }
                        else
                        {
                            Directory.CreateDirectory(dir);
                        }
                    }
                }
             }
 
            // Clears the text boxes.
            foreach (Control cont in this.Controls)
            {
                if (cont is TextBox)
                {
                    ((TextBox)cont).Text = string.Empty;
                }
            }
 
        }
 
        private void btnClear_Click(object sender, EventArgs e)
        {
            // Clears the text boxes.
            foreach (Control cont in this.Controls)
            {
                if (cont is TextBox)
                {
                    ((TextBox)cont).Text = string.Empty;
                }
            }
        }
 
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox1 myNewForm = new AboutBox1();
            myNewForm.ShowDialog();
        }
 
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
 
    }
}

Open in new window

already-exists.jpg
ASKER CERTIFIED SOLUTION
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of mrcoulson
mrcoulson
Flag of United States of America image

ASKER

Yes!  That works beautifully!  But why?  Can you take a second to explain it to me?  What is happening in the flow of the program that requires that extra if block?

Also, I don't think the trailing \ will matter because I am getting the path from a dialog box and Windows doesn't seem to return a \ after the end of the path.  Correct?
Maybe an upper/lower case problem.
Just didn't like the trick of comparing against the rootpath, when you simply can compare for empty or nullity.
Avatar of mrcoulson
mrcoulson
Flag of United States of America image

ASKER

Yes.  And this is how I learn!  Thanks!

Jeremy
.NET Programming
.NET Programming

The .NET Framework is not specific to any one programming language; rather, it includes a library of functions that allows developers to rapidly build applications. Several supported languages include C#, VB.NET, C++ or ASP.NET.

137K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo