JayGatsby
JayGatsby

Reputation: 1621

Creating valid file extension list

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?

Upvotes: 0

Views: 1941

Answers (2)

sujith karivelil
sujith karivelil

Reputation: 29036

 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]);
                      }

Upvotes: 0

Hamid Pourjam
Hamid Pourjam

Reputation: 20764

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

Upvotes: 3

Related Questions