How can I read all files from directory c#?

23,080

Solution 1

foreach (string fileName in Directory.GetFiles("directoryName", "searchPattern")
{
    string[] fileLines = File.ReadAllLines(fileName);
    // Do something with the file content
}

You can use File.ReadAllBytes() or File.ReadAllText() instead of File.ReadAllLines() as well, it just depends on your requirements.

Solution 2

        var searchTerm = "SEARCH_TERM";
        var searchDirectory = new System.IO.DirectoryInfo(@"c:\Test\");

        var queryMatchingFiles =
                from file in searchDirectory.GetFiles()
                where file.Extension == ".txt"
                let fileContent = System.IO.File.ReadAllText(file.FullName)
                where fileContent.Contains(searchTerm)
                select file.FullName;

        foreach (var fileName in queryMatchingFiles)
        {
            // Do something
            Console.WriteLine(fileName);
        }

This is a solution based on LINQ, which should also solve your problem. It might be easier to understand and easier to maintain. So if you are able to use LINQ give it a try.

Share:
23,080
icebox19
Author by

icebox19

Updated on July 09, 2022

Comments

  • icebox19
    icebox19 almost 2 years

    This is what I want to do:

    1. Select a directory
    2. Input a string
    3. Read all files from that directory in a string.

    The idea that I wanna implement is this:

    Select the directory, and input a string. Go to each file from that folder. For example the folder is: Directory={file1.txt,file2.txt,file3.txt}

    I wanna go to file1.txt first, read all the text, into a string, and see if my string is in that file. If yes: do else go to file2.txt, and so on.

    • Arran
      Arran almost 12 years
      Some SO users will give you the code you need straight away, but for the sake of everybody, please read this website: whathaveyoutried.com SO will not always give you the straight answer you want, you will have to do some work too.
  • icebox19
    icebox19 almost 12 years
    thanks, I get this error ... Error 1 The name 'File' does not exist in the current context
  • icebox19
    icebox19 almost 12 years
    I get this error ... Error 1 The name 'File' does not exist in the current context should I add something ?
  • eyossi
    eyossi almost 12 years
    Yea, add 'using System.IO;' next to the other using statements on top of the file
  • JaggenSWE
    JaggenSWE almost 12 years
    Nice, I also edited the code slightly and did a test compile. :)