使用 app.config 个文件创建一个文件夹

Create a folder with app.config file

我想创建一个Windows文件夹,文件夹的名称将从用户填写的TextBox.Text中获取,但在此文件夹内它还应该自动创建一个app.config

这是我目前得到的:

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);
}

我该怎么做?

这个怎么样:

public void SubmitButton_Click(object sender, EventArgs args)
{
    var name = CustomerTextBox.Text
    if (String.IsNullOrWhiteSpace(name)) 
    {
          MessageBox.Show("Enter a customer name!");
          return;
    }
    var result = CreateNewCustomer(name);        

    if (result) 
    {
        MessageBox.Show("You have successfully added a customer", "Customer added", MessageBoxButtons.OK);
    } 
    else 
    {
        MessageBox.Show("Something went wrong.", "Customer add failed", MessageBoxButtons.OK);
    }
}


private bool CreateNewCustomer(string customerName)
{
    var result = true;

    try 
    {
        var basepath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Customers");
        var custPath = System.IO.Path.Combine(basepath, customerName);
        var appconfigpath = System.IO.Path.Combine(custPath, "app.config");

        if (!System.IO.Directory.Exists(custPath)) 
        {
            System.IO.Directory.CreateDirectory(custPath);
        }
        System.IO.File.Create(appconfigpath);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Trace.TraceError("Error creating customer folder: {0}", ex);
        result = false;
    }    

    return result;
}

您应该有一个变量来保存是否创建新文件夹和 app.config 文件的根路径,例如 string root = Environment.CurrentDirectory。那么 CreateNewCustomer 方法将如下所示:

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);
    }     
}