2012-11-22 65 views
1

我正在做一個練習,我需要在一組文件中找到一個字符串。使用OpenFileDialog和Multiselect搜索字符串

我設法找到單獨選擇每個文件的字符串。 我該怎麼做一次選擇所有文件。

openFileDialog.Multiselect = true; 
DialogResult result = openFileDialog.ShowDialog(); 
string filename = openFileDialog.SafeFileName; 
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); 
BufferedStream bs = new BufferedStream(fs); 

StreamReader sr = new StreamReader(fs); 
String s; 
if (result == DialogResult.OK) 
{ 
    while ((s = sr.ReadLine()) != null) 
    { 
     if(s.Contains("Specified string")) 
     { 
      MessageBox.Show(filename + " Contains the Specified string"); 
      break; 
     } 
    } 

} 
fs.Close(); 
sr.Close(); 

回答

0

首先,你應該使用SafeFileNames Property

if (result == DialogResult.OK) 
{ 
    foreach(string filename = openFileDialog.SafeFileName) 
    { 
     FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); 
     BufferedStream bs = new BufferedStream(fs); 

     StreamReader sr = new StreamReader(fs); 
     String s; 

      while ((s = sr.ReadLine()) != null) 
      { 
       if(s.Contains("Specified string")) 
       { 
        MessageBox.Show(filename + " Contains the Specified string"); 
        break; 
       } 
      } 

     fs.Close(); 
     sr.Close(); 
    } 
} 

對於第二,你可以使用Parallel Class爲文件的同時處理。