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.
str.Write(allFiles[i] + Environment.NewLine);. Run through it until the value ofallFiles[i]is a file you don't want added to the file (yes, this may take a while and will be tedious and boring). What is the exact value ofallFiles[i]when that occurs?however, there are a few cases where these files manage to show up within the text document.Can you share those few cases with us?dirListPathbefore running your code? I have a sneaking suspicion that usingOpenOrCreatemeans you are writing to the start of the file but that the old contents of the file might be left there, so perhaps you are seeing old text in the file? One way to test my theory would be writeTHIS IS TO THE ENDto the stream outside of the loop and then see where that ends up in the file._