嗨,我对 c# 很陌生,所以对此表示歉意。
我试图创建一个文本文件来保存客户的详细信息。但我想用姓氏命名文本文件。即 myfile.txt。
我确定我很接近,但是在将 surname.text 更改为变量然后使其成为我创建的新文件的名称时缺少一些东西。
我在问题区域周围放置了 2 **。
private void button1_Click(object sender, EventArgs e)
{
try
{
if ((tb_firstname.Text == "") || (tb_surname.Text == "") || (tb_postcode.Text == ""))
{
MessageBox.Show("Missing values from textboxes!");
}
else if (
****string myfile.txt = (tb_surname.Text);
File.Exists("myfile.txt"));****
{
if (MessageBox.Show("Warning: file already exists. " +
"Contents will be replaced - " +
"do you want to continue?", "File Demo",
MessageBoxButtons.YesNo, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button1,
MessageBoxOptions.DefaultDesktopOnly) ==
DialogResult.Yes)
{
//write lines of text to file
StreamWriter outputStream = File.CreateText(myfile.txt);
outputStream.WriteLine(tb_firstname.Text);
outputStream.WriteLine(tb_surname.Text);
outputStream.WriteLine(tb_surname.Text);
outputStream.Close();
MessageBox.Show("Text written to file successfully!");
this.Close();
}
else
{
MessageBox.Show("Action cancelled existing file contents not replaced!");
this.Close();
}
}
else
{
//write lines of text to file
StreamWriter outputStream = File.CreateText("myFile.txt");
outputStream.WriteLine(tb_firstname.Text);
outputStream.WriteLine(tb_surname.Text);
outputStream.WriteLine(tb_postcode.Text);
outputStream.Close();
MessageBox.Show("Text written to file successfully!");
this.Close();
}
}
catch (Exception problem)
{
MessageBox.Show("Program has caused an error - " + problem.ToString());
}
}
任何帮助都会很棒!