[英]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我想创建一个 Windows 文件夹,该文件夹的名称将从用户将填写的TextBox.Text
中获取,但在此文件夹中它也应该自动创建一个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?我怎样才能做到这一点?
You should have a variable that holds the root path whether to create the new folder and the app.config file, eg, string root = Environment.CurrentDirectory
.您应该有一个变量来保存是否创建新文件夹和 app.config 文件的根路径,例如string root = Environment.CurrentDirectory
。 Then the CreateNewCustomer method would look like:然后 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);
}
}
How about this:这个怎么样:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.