2012-06-20 45 views
0

我想要做的是打开多个文件并从每个文件中读取文本并检查某些关键字并将它们全部打印到一个新文件中,并且一旦完成将使用所有关键字创建新文件。我已经使用foreach遍历所有的文件名,并且我知道如何打开多个文件,但是如何在打印时检索内容并检查特定条件?在C#中打开多个文件并检查每个文件的内容

下面只是一个我到目前为止,很标准的东西的例子。

谢谢你们!

if (dr == System.Windows.Forms.DialogResult.OK) 
     { 
      // Read the files 
      foreach (String file in openFileDialog1.FileNames) 
      { 

       try 
       { 

        listView1.Items.Add(file); 

       } 
       catch (SecurityException ex) 
       { 
        // The user lacks appropriate permissions to read files, discover paths, etc. 
        MessageBox.Show("Security error. Please contact your administrator for details.\n\n" + 
         "Error message: " + ex.Message + "\n\n" + 
         "Details (send to Support):\n\n" + ex.StackTrace 
        ); 
       } 
       catch (Exception ex) 
       { 
        // Could not load the image - probably related to Windows file system permissions. 
        MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\')) 
         + ". You may not have permission to read the file, or " + 
         "it may be corrupt.\n\nReported error: " + ex.Message); 
       } 

      } 

     } 
+1

这应该标记为功课? – PedroC88

回答

1

要读取文件使用System.IO.File.ReadAllText()。这将把所有的内容放入一个字符串变量中。

0
Try 
      Using sr As New StreamReader("TestFile.txt") 
       Dim line As String 
       Do 
        line = sr.ReadLine() 
        If Not (line Is Nothing) Then 
         Console.WriteLine(line) 
        End If 
       Loop Until line Is Nothing 
      End Using 
     Catch e As Exception 
      Console.WriteLine("The file could not be read:") 
      Console.WriteLine(e.Message) 
     End Try 

背出写;)

相关问题