Search code examples
c#winformsapp-config

Create a folder with app.config file


I want to create a Windows Folder the name of the folder will get it from a TextBox.Text that the user will fill in, but inside this folder it should also create automatically an app.config

This is what I got so far:

private void CreateNewCustomer()
{
    Directory.CreateDirectory(@"C:\Users\khaab\Documents\visual studio 2015\Projects\ReadingXML\ReadingXML\bin\Debug\Customers\" + CustomerTextBox.Text);
    StreamWriter File = new StreamWriter(@"C:\Users\k.abdulrazak\Documents\visual studio 2015\Projects\ReadingXML\ReadingXML\bin\Debug\Customers\app.config");
    File.Close();
    MessageBox.Show("You have successfully added a customer", "Customer added", MessageBoxButtons.OK);
}

How can I do that?


Solution

  • You should have a variable that holds the root path whether to create the new folder and the app.config file, e.g., string root = Environment.CurrentDirectory. Then the CreateNewCustomer method would look like:

    public void CreateNewCustomer()
    {
        var di = Directory.CreateDirectory(Path.Combine(root, CustomerTextBox.Text));
        if (di.Exists)
        {
            var fs = File.Create(Path.Combine(di.FullName, "app.config"));
            fs.Close();
            MessageBox.Show("You have successfully added a customer", "Customer added", MessageBoxButtons.OK);
        }     
    }