1

我是WPFand的初学者C#。我正在尝试做电话簿作业。我不知道通过每次单击在文本文件中添加项目的语法。对不起,因为我的问题。

public MainWindow()
    {
        InitializeComponent();
        System.IO.File.CreateText(@"E:\MYText.txt");
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {

        string Name01 = NameBox.Text;
        string Name02 =FamilyNameBox.Text;
        string Name03 = PhoneBox.Text;
        string Informtion = Name01 + Name02 + Name03;
        NameBox.Clear();
        FamilyNameBox.Clear();
        PhoneBox.Clear();
        System.IO.StreamWriter MyWriter = new System.IO.StreamWriter(@"E:\MYText.txt", true);
        MyWriter.Write(Informtion);
        MyWriter.Close();
    }
4

2 回答 2

1

尽量不要使用 StreamWriter。改为这样做。

List<string> textLines = new List<string>();
string Name01 = NameBox.Text;
string Name02 =FamilyNameBox.Text;
string Name03 = PhoneBox.Text;
string Informtion = Name01 + Name02 + Name03;   
textLines.Add(Information);
// add more lines if you want.
File.WriteAllLines(fileName, textLines);

如果要在其他文件中附加文本,也可以使用 File.AppendAllLines(fileName, textLines)。

于 2013-01-28T06:40:35.023 回答
0

I got from one of my apps that writes file, this works 100% adapting to your code

using System.IO;//don't forget to reference the IO package
    TextWriter writer = new StreamWriter("class1.txt");
        try
        {
           string Name01 = NameBox.Text;
           string Name02 =FamilyNameBox.Text;
           string Name03 = PhoneBox.Text;
           string Informtion = Name01 + Name02 + Name03;        
           writer.WriteLine(Informtion);
        }
        catch(Exception ex)
        {
            throw ex;
        }
        finally
        {
            writer.Close();
            writer.Dispose();
        }
于 2013-01-28T06:33:12.547 回答