0

从以下代码中,我尝试将 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!");

                }
        }
4

2 回答 2

0

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

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);               
            }
        }   
    }
于 2017-10-15T17:36:07.043 回答
0

我已经通过创建一个新文件对其进行了整理。

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();
        }
    }
于 2017-10-15T18:15:48.317 回答