C#让StreamWriter写入文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16127256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:05:33  来源:igfitidea点击:

C# Getting StreamWriter to Write to text file

c#windowsforms

提问by webby68

I have reviewed my Professor's lecture numerous times, reviewed the text book, searched endlessly online for answers, and tried every reasonable suggested fix out there. I am certainly missing something. The address book writes to the list box, the file is created, but the name and address is not written to the file. Any help with what I am missing would be greatly appreciated.

我已经多次复习我教授的讲座,复习课本,在网上无休止地搜索答案,并尝试了所有合理的修复建议。我肯定错过了一些东西。地址簿写入列表框,创建文件,但名称和地址未写入文件。对我所缺少的任何帮助将不胜感激。

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)
        {

        }
    }
}

采纳答案by Alexei Levenkov

You are saving data to file on form load when all fields are empty. Move writing code to some button click handler after you have chance to type values in the text fields.

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

You are also using version of TextWriter.WriteLinemethod that take format as first argument. Unless you really want to do that either 2 separate WriteLinecalls or one with correct format string would probably do what you want.

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

Also make sure to close/dispose your stream writer so it commits changes to file and closes the file. Usual way to do that is to use using:

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

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

回答by Gjeltema

Try either calling Flush or Close on the stream. Best practice is to wrap it in a using though.

尝试在流上调用 Flush 或 Close。最佳做法是将其包装在 using 中。

using(StreamWriter address = new StreamWriter("addressbook.txt"))
{
    ...
}

http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx

http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx

Scroll down to the example code.

向下滚动到示例代码。

回答by KF2

You forgot to add complete address,try this:

您忘记添加完整地址,试试这个:

 private void Window_Loaded(object sender, RoutedEventArgs e)
    {

        try
        {

           using (StreamWriter address = new StreamWriter("d:\addressbook.txt"))//Add correct address
            {
              address.WriteLine(textBox1.Text + textBox2.Text);
              //OR
              address.WriteLine(string.Format("Name:{0}, Email:{1}", textBox1.Text,    textBox2.Text));
            }
        }
        catch (DirectoryNotFoundException exc)
        {
            MessageBox.Show("Directory Could Not Be Found");
        } 
    }