【问题标题】:Writing List items to text file c#将列表项写入文本文件c#
【发布时间】:2014-05-05 18:48:59
【问题描述】:

我正在尝试将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 中显示名字和姓氏。这也是我的 Employee 类:

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);
    }
}

【问题讨论】:

  • 什么是employeeListitem 是什么?
  • 这些附加信息从何而来?它就像您的代码正在执行您所要求的那样,保存列表的内容。
  • 我们需要更多的数据。 var 项是什么类型?什么是employeeList?我的第一个线索是 item.ToString() 仅返回 @item type@ 的特定属性而不是所有属性...您需要覆盖 item.ToString() 方法以返回更多。
  • 您使用List&lt;dynamic&gt; 而不是List&lt;Employee&gt; 是否有原因?
  • 其实不,那是一个错字。我现在确实有 List

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


【解决方案1】:

当你调用SaveFile.WriteLine(item.ToString());时,你写的是EmployeeToString()方法的结果:

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

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

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

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

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

【讨论】:

  • 非常感谢!我看着那条线试图弄清楚它是否是我的罪魁祸首。现在完美运行!
猜你喜欢
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-19
  • 2017-11-06
  • 2017-09-27
  • 1970-01-01
  • 2020-04-20
相关资源
最近更新 更多