我想创建一个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);
}
我该怎么做?
答案 0 :(得分:1)
您应该拥有一个包含根路径的变量,无论是创建新文件夹还是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);
}
}
答案 1 :(得分:0)
这个怎么样:
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;
}