Hi im very new to c# so apologies for this.
Im trying to create a text file to save customers details. But i want to name the text file by the surname. I.e myfile.txt.
Im sure im close, but missing something when it comes to changing the surname.text to a variable then making it the name of my created new file.
I have put 2 ** around the problem area.
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());
}
}
any help would be great!