Search code examples
c#directorycontainsgetfiles

Contains function doesn't find specific files in sub directories


I created a string array that utilizes the Directory.GetFiles function which populates the array with .cs file extensions from all sub directories in my project. This is fine, however, I was trying to write these files to a text document while excluding specific files from the array such as "AssemblyInfo.cs" and "TemporaryGeneratedFiles_xxx.cs" using the contains method to filter files with these names. For the most part, the large majority of these files were not written to the text document, however, there are a few cases where these files manage to show up within the text document.

I've tried using a foreach statement instead of a for loop. I've tried playing around with the str.flush(), str.close(), directoryNames.Dispose(), and directoryNames.Close() by putting them in different spots of the for loop. I tried nesting the if statements instead of using the && operator. The || operator doesn't work in this situation. I've tried using the entire file name and only bits and pieces of the file name and none of this seems to work. At one point I did manage to remove all file that had "Temporary" in it but the "AssemblyInfo.cs" files still remain. I even made a method to completely remove anything with the word temporary or assembly in its file name but that also failed.

FileStream directoryNames = new FileStream(dirListPath, FileMode.OpenOrCreate);
StreamWriter str = new StreamWriter(directoryNames);

string[] allFiles = Directory.GetFiles(dirPath, "*.cs", SearchOption.AllDirectories);

for (int i = 0; i < allFiles.Length; i++)
{
    if ((!allFiles[i].Contains("Temporary")) && (!allFiles[i].Contains("Assembly")))
    {
        str.Write(allFiles[i] + Environment.NewLine);
    }
}
str.Flush();
str.Close();
directoryNames.Dispose();
directoryNames.Close();

No error messages occur but as stated above unexpected files pop up where they shouldn't be. Any help would be greatly appreciated.


Solution

  • Thanks to everyone who posted. After some testing mjwillis was correct. Instead of overwriting the contents in the text file it kept writing to the top of the file and adding on to the contents that were written previously. Fixed it by adding

    using (FileStream clearTextDocument = File.Create(dirListPath)) { }
    

    Before the FileStream DirectoryNames line. Feel free to post another way to clear a text document if it's more attractive than this.