拥有和使用可配置的允许文件扩展名列表的最佳方法是什么?

Ron*_*ona 0 c# asp.net file-extension

我有以下内容:

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

if (_file.EndsWith("xls") || _file.EndsWith("pdf") || _file.EndsWith("doc")) 
    return _file;
Run Code Online (Sandbox Code Playgroud)

该扩展是硬编码的,我需要把它们web.config并使其在某种程度上更可配置的,它可以有1允许扩展名(比方说.doc)或50个允许扩展(.doc,.xls,.xlsx,.ppt,...).

你有什么建议?

Gra*_*ICA 6

您可以将其存储在web.config文件中:

<appSettings>
    <add key="AllowedExtensions" value=".xls,.pdf,.doc" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)

然后使用Path.GetExtension()从路径安全地获取文件扩展名.

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?
Run Code Online (Sandbox Code Playgroud)