C#让StreamWriter写入文本文件

web*_*y68 0 c# forms windows

我已经多次回顾了我教授的讲座,回顾了教科书,在网上无休止地搜索了答案,并尝试了所有合理的建议.我当然错过了一些东西.地址簿写入列表框,文件已创建,但名称和地址未写入文件.任何有关我缺少的帮助将不胜感激.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.IO;


namespace LAB7A
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }


        List<Person> people = new List<Person>();
        class Person
        {
            public string Name
            {
                get;
                set;
            }

            public string Email
            {
                get;
                set;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            try
            {
               StreamWriter address = new StreamWriter("addressbook.txt");
               address.WriteLine(textBox1.Text, textBox2.Text);
            }
            catch (DirectoryNotFoundException exc)
            {
                MessageBox.Show("Directory Could Not Be Found");
            }
        }

        private void button1_Click(object sender, System.EventArgs e)

        {

            Person p = new Person();
            p.Name = textBox1.Text;
            p.Email = textBox2.Text;
            people.Add(p);
            listBox1.Items.Add(p.Name);
            listBox1.Items.Add(p.Email);



            //StreamWriter address.WriteLine(textBox1.Text);
            //address.WriteLine(textBox2.Text);
            //listBox1.Items.Add(textBox1.Text);
            //listBox1.Items.Add(textBox2.Text);
        }

        private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
        {

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*kov 6

当所有字段都为空时,您将在表单加载时将数据保存到文件.在有机会在文本字段中键入值后,将编写代码移动到某个按钮单击处理程序.

您还使用将格式作为第一个参数的TextWriter.WriteLine方法的版本.除非你真的想这样做,否则两个单独的WriteLine调用或一个具有正确格式字符串的调用可能会做你想要的.

还要确保关闭/处置您的流编写器,以便将更改提交到文件并关闭文件.通常的方法是使用using:

using (var writer = new StreamWriter("addressbook.txt"))
{
     writer.WriteLine("First textbox:{0}, second:{1}", textBox1.Text, textBox2.Text);
}
Run Code Online (Sandbox Code Playgroud)