簡體   English   中英

將ListView項目保存在C#的文本文件中

[英]Saving ListView items in a text file in c#

從以下代碼中,我試圖將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!");

                }
        }

嘗試將代碼更改為以下版本,看看是否可行:

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

我已經通過創建一個新文件對其進行了整理。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM