如何将TextBoxes值保存到多行文本文件中

时间:2018-03-07 06:22:04

标签: c# text save multiline

请参阅下文

我的表单有多个文本框

enter image description here

我想将值保存到一个包含多行文本文件的文本文件中。

但我的代码似乎不起作用。它仅将值保存为一个字符串。 我想按行保存它

实施例。我想要实现的目标

enter image description here

请参阅下面的代码

   SaveFileDialog save = new SaveFileDialog();

        save.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

            if (save.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                StreamWriter write = new StreamWriter(File.Create(save.FileName));



                write.Write(X1TB.Text.Replace(Environment.NewLine, @" \n "));
                write.Write(X2TB.Text.Replace(Environment.NewLine, @" \n "));
                write.Write(X3TB.Text.Replace(Environment.NewLine, @" \n "));
                write.Write(X4TB.Text);
                write.Write(X5TB.Text);
                write.Write(X6TB.Text);
                write.Write(X7TB.Text);
                write.Write(X8TB.Text);
                write.Write(X9TB.Text);
                write.Write(X10TB.Text);
                write.Write(X11TB.Text);
                write.Write(X12TB.Text);
                write.Write(X13TB.Text);
                write.Write(X14TB.Text);
                write.Write(X15TB.Text);
                write.Write(X16TB.Text);
                write.Write(X17TB.Text);
                write.Write(X18TB.Text);
                write.Write(X19TB.Text);
                write.Write(X20TB.Text);

                write.Dispose();

                MessageBox.Show("The file is now saved!", "Successful!");

提前感谢那些愿意帮助的人。

3 个答案:

答案 0 :(得分:0)

如果这些是您正在使用的唯一文本框,则可以简化代码,如下所示:

.replace()

答案 1 :(得分:0)

试试这个

    write.WriteLine(X1TB.Text);
    write.WriteLine(X2TB.Text);
    write.WriteLine(X3TB.Text);
    write.WriteLine(X4TB.Text);
    write.WriteLine(X5TB.Text);
    write.WriteLine(X6TB.Text);
    write.WriteLine(X7TB.Text);
    write.WriteLine(X8TB.Text);
    write.WriteLine(X9TB.Text);
    write.WriteLine(X10TB.Text);
    write.WriteLine(X11TB.Text);
    write.WriteLine(X12TB.Text);
    write.WriteLine(X13TB.Text);
    write.WriteLine(X14TB.Text);
    write.WriteLine(X15TB.Text);
    write.WriteLine(X16TB.Text);
    write.WriteLine(X17TB.Text);
    write.WriteLine(X18TB.Text);
    write.WriteLine(X19TB.Text);
    write.WriteLine(X20TB.Text);

答案 2 :(得分:0)

这是我的工作方式

  

System.IO.File.WriteAllLines(@"C:\TextFile1.txt", new string[] { "1", "2", "3", "4" });

看起来像是

1
2
3
4