RonaDona RonaDona - 3 months ago 26
ASP.NET (C#) Question

What is the best way to have and use a configurable list of allowable file extensions?

I have the following:

string _file; //can have any file path on the file server

if (_file.EndsWith("xls") || _file.EndsWith("pdf") || _file.EndsWith("doc"))
return _file;

The extensions are hard coded and I need to put them in
and make it more configurable in a way that it can have 1 allow extension (say
) or 50 allowed extensions (
, ...).

What do you suggest?


You could store it in the web.config file:

    <add key="AllowedExtensions" value=".xls,.pdf,.doc" />

Then use Path.GetExtension() to safely get the file extension from the path.

var allowedExtensions = ConfigurationManager.AppSettings["AllowedExtensions"]

if (allowedExtensions.Contains(Path.GetExtension(_file)))
    return _file;
    return ???  // What are you going to return if the extension is invalid?