Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Folder validation

Tags:

c#

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?

like image 600
007 Avatar asked Apr 20 '26 05:04

007


2 Answers

  1. Change excludeSubFolders to be string[] array:

    string[] excludeSubFolders = new [] { "SubFolderA", "SubFolderB", "SubFolderC", "SubFolderABC" };
    
  2. Use Contains method:

    foreach (DirectoryInfo folder in directories)
       if (!excludeSubFolders.Contains(folder.Name))
          {...}
    
  3. To get string[] from single string use String.Split() method:

    var subFolders = input.Split(',').Select(x => x.Trim()).ToArray();
    
like image 154
MarcinJuraszek Avatar answered Apr 21 '26 20:04

MarcinJuraszek


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())))
{
    // ...
}
like image 36
Phil K Avatar answered Apr 21 '26 21:04

Phil K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!