Search code examples
c#winformsopenfiledialog

Opening multiple files in C# and checking the contents of every file


What I want to do is open multiple files and read in the text from every file and check for certain keywords and print them all into a new file, and once done a new file will be created with all of the keywords. I am already using a foreach to iterate through all the file names and I know how to open multiple files, but what about retrieving the contents and checking certain conditions while simultaneously printing?

Below is just an example of what I have so far, pretty standard stuff.

Thanks guys!

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

            }

        }

Solution

  • You read a file using System.IO.File.ReadAllText() like SoMoS suggests. Search the string in whatever way works best and write the data back out with a StreamWriter