首页> C#>如何创建一个文本文件,并用一个文本框或变量命名

嗨,我对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());
        }
}

任何帮助将是巨大的!

解决方法:

每次创建一个名为myfile.txt的文件

StreamWriter outputStream = File.CreateText("myFile.txt");

这是您正在使用的字符串文字.

您有一行:

string myfile.txt = (tb_surname.Text)

它将文本框的内容读取到名为myfile.txt的变量中.然后,您需要在文件创建代码中使用它:

StreamWriter outputStream = File.CreateText(myFile.txt);

请注意没有引号.

如果文件已经存在,这将覆盖该文件-如果要添加文件,则需要使用以下方法:

StreamWriter outputStream = File.AppendText(myFile.txt);
上一篇:SQL SERVER 查询历史执行语句


下一篇:N-API中的Promise功能的使用