C# : Create Folder by Code (runtime)

Hi coder! 🙋

Creating a folder by C# code will be the topic of this post. I also include checking if the folder has already existed before.

I will use a root folder/directory for this sample. I create an empty folder named "upload" on D drive. So the path will be D:/upload. 


For this sample, I've already had a desktop application with C# named CSharpSample. Set the UI as below, there are 3 controls which are a Label, a Textbox, and a button.



For coding, you'll need to add "using System.IO". And the complete code is below:

using System;
using System.IO;
using System.Windows.Forms;

namespace CSharpSample
{
    public partial class Form1 : Form
    {
        //lokasi folder ditempatkan
        string root = @"D:\upload\";

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = "Root : " + root;
            button1.Text = "Create";
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            string FolderName = root + textBox1.Text;
            if (!Directory.Exists(FolderName)) {
                Directory.CreateDirectory(FolderName);
                MessageBox.Show(textBox1.Text + " folder created!");
            } else
            {
                MessageBox.Show(textBox1.Text + " has already exist!");
            }
        }
    }
}


Finished with the code, try to run debug. Type a name for folder to be created (e.g. rani), then click Create button. 



Because folder that named "rani" is not exist before, after creating the message will prompt "rani folder created!"


Let's have a check on window explorer whether the new folder has already existed or not.



Now let's try to recreate the existing folder. After create button is clicked a message will display "rani has already exist!"


Download sample project here!






Post a Comment

0 Comments