0

I'm applying a function to specific file formats

string extension = Path.GetExtension(files[i]);
if (extension == ".txt")
{
    DoSomething(files[i]);
}

But I have too many file extension, not only txt. What is the basic way to create a white list and check if it's included on that list?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
JayGatsby
  • 1,541
  • 6
  • 21
  • 41

2 Answers2

3

you can create a white list and check if extension is inside it or not

var whitelist = new[]
{
    ".txt", ".bat", ".con"
};

string extension = Path.GetExtension(files[i]);
if (whitelist.Contains(extension))
{
    DoSomething(files[i]);
}

if your white list size becomes large (more than 20) try using HashSet for better performance

Community
  • 1
  • 1
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
0
 List<string> fileExtensions = new List<string>();
                      fileExtensions.AddRange(".txt,.png,.bmp,.pdf".Split(','));
                      string extension = Path.GetExtension(files[i]);
                      if (fileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase))
                      {
                        //  DoSomething(files[i]);
                      }
Paul Williams
  • 95
  • 2
  • 11
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88