2016-03-03 56 views
0

我在* .cs文件的目录中搜索特定的字符串。 如果我将它添加到列表视图中。 但是,当它将结果添加到列表视图我没有看到CS文件名字符串被发现,但其他东西。为什么添加到列表视图项目时,结果不是文件名?

在BackgroundWorker的DoWork的事件

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
     { 
      FindLines(@"d:\c-sharp", "simplecontextmenu");//"string s1 = treeView1.SelectedNode.Tag as string;"); 
     } 

这是FindLines代码

bool result = false; 
     public List<string> FindLines(string DirName, string TextToSearch) 
     { 
      int counter = 0; 
      List<string> findLines = new List<string>(); 
      DirectoryInfo di = new DirectoryInfo(DirName); 

      List<FileInfo> l = new List<FileInfo>(); 
      CountFiles(di, l); 

      int totalFiles = l.Count; 
      int countFiles = 0; 
      if (di != null && di.Exists) 
      { 
       if (CheckFileForAccess(DirName) == true) 
       { 
        foreach (FileInfo fi in l) 
        { 
         backgroundWorker1.ReportProgress((int)((double)countFiles/totalFiles * 100.0), fi.Name); 
         countFiles++; 
         System.Threading.Thread.Sleep(1); 

         if (string.Compare(fi.Extension, ".cs", true) == 0) 
         { 
          using (StreamReader sr = fi.OpenText()) 
          { 
           string s = ""; 
           while ((s = sr.ReadLine()) != null) 
           { 
            if (s.Contains(TextToSearch)) 
            { 
             counter++; 
             findLines.Add(s); 
             result = true; 
             backgroundWorker1.ReportProgress(0, s); 
            } 
           } 
          } 
         } 
        } 
       } 
      } 
      return findLines; 
     } 

这是BackgroundWorker的progresschanged事件

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 
     { 
      progressBar1.Value = e.ProgressPercentage; 
      label2.Text = e.UserState.ToString(); 
      if (result == true) 
      { 
       listView1.Items.Add(e.UserState.ToString()); 
       result = false; 
      } 
     } 

一些与在FindLines方法ReportProgress并在progresschanged事件中使用e.UserState是错的。我没有得到在列表视图中找到字符串的cs文件的路径和名称。

我在这个目录中搜索字符串“simplecontextmenu”,如果字符串在目录中的任何一个cs文件中,我想添加到listview中的文件名字符串在该目录中找到例如,如果串在test.cs中找到,那么在列表视图告诉我:

C:\ mytest的\ test.cs中“simplecontextmenu”

但我得到的却是该行自它从代码是什么我在listview中看到的是:FindLines(@“d:\ c-sharp”,“simplecontextmenu”); //“string s1 = treeView1.SelectedNode.Tag as string;”);

回答

1

您要举报的backgroundWorker1.ReportProgress(0, s);匹配的行s。您应该报告文件名:

backgroundWorker1.ReportProgress(0, fi.FullName);

相关问题