RonaDona RonaDona - 9 days ago 9
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
web.config
and make it more configurable in a way that it can have 1 allow extension (say
.doc
) or 50 allowed extensions (
.doc
,
.xls
,
.xlsx
,
.ppt
, ...).

What do you suggest?

Answer

You could store it in the web.config file:

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

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

var allowedExtensions = ConfigurationManager.AppSettings["AllowedExtensions"]
                                            .Split(',');

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