将列表项写入文本文件c#

时间:2014-05-05 18:49:00

标签: c# list listbox text-files save-as

我正在尝试将List保存到文本文件中并遇到问题。 它将保存到文本文件中,但不会根据需要保存所有信息,而只保存ListBox中实际显示的信息。建议?

namespace Employee_Form
{
public partial class frmMain : Form
{
    FileStream output;
    StreamReader fileReader;
    //StreamWriter fileWriter;
    List<Employee> employeeList = new List<Employee>();


    public frmMain()
    {
        InitializeComponent();
    }

    private void frmMain_Load(object sender, EventArgs e)
    {

    }

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFile();
    }

    private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        SaveAs();
    }

    private void addNewToolStripMenuItem_Click(object sender, EventArgs e)
    {
        PropertiesOpen();
    }

    private void PropertiesOpen()
    {

        //creates an instance of the Properties Form
        frmProperties myform = new frmProperties();
        DialogResult result = myform.ShowDialog();
    }


    //Opens a file chosen by a user and places information into the listbox
    private void OpenFile()
    {

        OpenFileDialog fileChooser = new OpenFileDialog();

        fileChooser.Title = "Pick a file";
        fileChooser.Filter = "Text Files (*.txt) | *.txt";

        DialogResult result = fileChooser.ShowDialog();

        //
        if (result == DialogResult.Cancel)
        {
            //do nothing
            return;
        }

        string strFileName = fileChooser.FileName;

        try
        {
            //open the file for read access
            output = new FileStream(strFileName, FileMode.Open, FileAccess.Read);

            fileReader = new StreamReader(output);

            //variables to hold read record
            string strInputLine;
            string[] fields;

            //loop to get records and break into fields
            while (fileReader.EndOfStream != true)
            {
                //read record
                strInputLine = fileReader.ReadLine();

                //split the records when read
                fields = strInputLine.Split(',');

                //add records to the list box 
                employeeList.Add(new Employee(fields[1], fields[0], fields[2], 
                                     Convert.ToDouble(fields[3])));

            }
            lstRecords.DataSource = employeeList;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            //closes fileReader and output to save Resources
            fileReader.Close();
            output.Close();
        }
    }

    public void SaveAs()
    {
        //create a file dialog
        SaveFileDialog fileChooser = new SaveFileDialog();
        fileChooser.Title = "Choose A Save Location";
        fileChooser.Filter = "Text Files (*txt)|*.txt";

        //open the dialog and get a result
        DialogResult result = fileChooser.ShowDialog();

        //checks if user clicks cancel
        if (result == DialogResult.Cancel)
        {
            return;
        }

        //get the file name from the dialog
        string strFileName = fileChooser.FileName;
        try
        {
            //open the new file for write access
            StreamWriter SaveFile = new StreamWriter(strFileName);

            foreach (var item in employeeList)
            {
                SaveFile.WriteLine(item.ToString());
            }
            SaveFile.Close();
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        finally
        {
            //close resources
            //fileWriter.Close();
            output.Close();
        }
    }
}

对不起,我是新来的。有两种形式,第二种用于编辑/添加新员工。只需要在ListBox中显示名字和姓氏。这是我的员工课程:

public class Employee
{
    public string FirstName
    {
        get;
        set;
    }

    public string LastName
    {
        get;
        set;
    }

    public string EmpType
    {
        get;
        set;
    }

    public double Salary
    {
        get;
        set;
    }

    public Employee(string firstName, string lastName, string empType, double salary)
    {
        FirstName = firstName;
        LastName = lastName;
        EmpType = empType;
        Salary = salary;
    }

    public override string ToString()
    {
        return string.Format("{0}, {1}", LastName, FirstName);
    }
}

1 个答案:

答案 0 :(得分:1)

当您致电SaveFile.WriteLine(item.ToString());时,您正在撰写ToString() Employee方法的结果:

return string.Format("{0}, {1}", LastName, FirstName);

这是ListBox调用以在列表中显示对象的方法。因此,您所看到的行为正是人们所期待的。

如果你想看到不同的东西,试试这样的事情:

SaveFile.WriteLine(string.Format("{0}, {1}, {2}, {3}", item.LastName, item.FirstName, item.EmpType, item.Salary));

在文件中使用您想要的任何属性和格式。