Marvin kakuru

Marvin kakuru

  • 1.3k
  • 324
  • 155.1k

check if a text exists in various txt files

Jul 31 2023 11:03 AM

Hello Guys,

i am trying to search a folder of txt. files for any txt.file containing the name "TOM" 

below is the code am trying to use

 static void Main(string[] args)
        {
            string startFolder = @"c:\Textfiles\";
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);
            IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
            string searchTerm = @"people";

            var queryMatchingFiles =
            from file in fileList
            where file.Extension == ".htm"
            let fileText = GetFileText(file.FullName)
            where fileText.Contains(searchTerm)
            select file.FullName;

            Console.WriteLine("The term \"{0}\" was found in:", searchTerm);
            

            foreach (string filename in queryMatchingFiles)
            {
                Console.WriteLine(filename);
            }

            // Keep the console window open in debug mode.  
            Console.WriteLine("Press any key to exit");
            Console.ReadKey(); 
        }

        static string GetFileText(string name)
        {
            string fileContents = String.Empty;

            // If the file has been deleted since we took
            // the snapshot, ignore it and return the empty string.  
            if (System.IO.File.Exists(name))
            {
                fileContents = System.IO.File.ReadAllText(name);
            }
            return fileContents;
        }  
    }


Answers (3)