2017-10-15 36 views
0

从下面的代码我试图保存listView项目在文本文件中。但它不保存文本文件中的listView项目,甚至不会产生任何错误。我的listView有一个列。请确定此代码中缺少的内容。在c中的文本文件保存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!"); 

       } 
     } 
+0

您能否提供调用saveAttemptsStatus函数的代码? –

+0

@ShaiAharoni我已添加该代码。 – Sumi

回答

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

存在同样的问题。 – Sumi

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