【问题标题】:Saving ListView items in a text file in c#在 C# 中将 ListView 项目保存在文本文件中
【发布时间】:2018-03-27 05:41:20
【问题描述】:

从以下代码中,我尝试将 listView 项目保存在文本文件中。但它不会将 listView 的项目保存在文本文件中,甚至不会产生任何错误。我的 listView 有一个列。请找出我在此代码中缺少的内容。

private void saveAttemptsStatus()
    {            
        var sw = new System.IO.StreamWriter("D:\\AlphaNumDataSum_" + txt_LUsername.Text);
        foreach (ListViewItem item in list_Count.Items)
        {

            sw.Write(item + "\r\n");               
        }
        sw.Close();
    }    
private void CountAttemps()
    {
        int numberOfItems = list_Count.Items.Count;
        if (numberOfItems != 10)
                {
                    if (username == txt_LUsername.Text && password == txt_LPassword.Text)
                    {
                        list_Count.Items.Add("correct");
                        txt_LUsername.Text = string.Empty;
                        txt_LPassword.Text = string.Empty;
                    }
                    else
                    {
                        list_Count.Items.Add("inCorrect");
                        txt_LUsername.Text = string.Empty;
                        txt_LPassword.Text = string.Empty;
                    }
                    }
                else
                {
                    saveAttemptsStatus();
                    MessageBox.Show("Thank You!");

                }
        }

【问题讨论】:

  • 能否提供调用 saveAttemptsStatus 函数的代码?
  • @ShaiAharoni 我已经添加了该代码。

标签: c# listview export-to-text


【解决方案1】:

尝试将您的代码更改为以下版本,看看是否可行:

private void saveAttemptsStatus()
    {    
        var filePath = "D:\\AlphaNumDataSum_" + txt_LUsername.Text;

        using(sw = new System.IO.StreamWriter(filePath)){

            foreach (ListViewItem item in list_Count.Items)
            {
              sw.WriteLine(item.Text);               
            }
        }   
    }

【讨论】:

  • 存在同样的问题。
【解决方案2】:

我已经通过创建一个新文件来解决它。

private void saveAttemptsStatus()
    {
        try
        {
            var sw = new System.IO.StreamWriter("D:\\AlphaNumDataSum_" + txt_LUsername.Text + "_Attempts");
            foreach (ListViewItem item in list_Count.Items)
            {
                sw.Write(item + "\r\n");
            }
            sw.Close();
        }
        catch (System.IO.FileNotFoundException ex)
        {
            System.IO.File.Create("D:\\AlphaNumDataSum_" + txt_LUsername.Text + "_Attempts");
            var sw = new System.IO.StreamWriter("D:\\AlphaNumDataSum_" + txt_LUsername.Text + "_Attempts");
            foreach (ListViewItem item in list_Count.Items)
            {
                sw.Write(item + "\r\n");
            }
            sw.Close();
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多