string excludeSubFolders = "SubFolderA, SubFolderB, SubFolderC, SubFolderABC";
DirectoryInfo directory = new DirectoryInfo(myRootFolderPath);
DirectoryInfo[] directories = directory.GetDirectories();
foreach (DirectoryInfo folder in directories)
if (folder.Name.ToString().Trim() != "SubFolderA")
{...}
A C# newbie here. Above is the code I am using to exclude "SubFolderA" which resides in my root folder (myRootFolderPath). I need to exclude all the sub-folders listed in excludeSubFolders variable.
Thank you
UPDATE: string excludeSubFolders is being populated through a parameter outside of c# code. I just listed the output of that parameter in the format c# is expecting. Also the parameter will have "SubFolderA, SubFolderB, SubFolderC, SubFolderABC" value today while the day after tomorrow, someone will change that to "SubFolderA, SubFolderB, SubFolderC" and call the same c# code. How will this work with the presented string array suggestions?
Change excludeSubFolders to be string[] array:
string[] excludeSubFolders = new [] { "SubFolderA", "SubFolderB", "SubFolderC", "SubFolderABC" };
Use Contains method:
foreach (DirectoryInfo folder in directories)
if (!excludeSubFolders.Contains(folder.Name))
{...}
To get string[] from single string use String.Split() method:
var subFolders = input.Split(',').Select(x => x.Trim()).ToArray();
First thing I'd do is change your excludeSubFolders to a string array, because that makes it much easier to work with:
string[] excludeSubFolders = new string[] { "SubFolderA", "SubFolderB", "SubFolderC", "SubFolderABC" };
then you can use LINQ to filter out the directories that match your exclusion array:
foreach (DirectoryInfo folder in directories.Where(dir => !excludeSubFolders.Contains(dir.Name.ToString().Trim())))
{
// ...
}
UPDATE: regarding the update to your question: if you are being handed a comma-delimited string and cannot use a string array, then you can split the string into a string array programatically:
string excludeSubFolders = "SubFolderA, SubFolderB, SubFolderC, SubFolderABC";
string[] excludeSubArray = excludeSubFolders.Split(new []{", "}, StringSplitOptions.RemoveEmptyEntries);
foreach (DirectoryInfo folder in directories.Where(dir => !excludeSubArray.Contains(dir.Name.ToString().Trim())))
{
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With