C# 拥有和使用可配置的允许文件扩展名列表的最佳方式是什么?
我有以下资料:C# 拥有和使用可配置的允许文件扩展名列表的最佳方式是什么?,c#,asp.net,file-extension,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; 扩展是硬编码的,我需要将它们放在web.config中,并使其更具可配置性,它可以有1个允许的扩展,例如.doc或50个允许的扩展.doc、.xls、.xlsx、.ppt等
string _file; //can have any file path on the file server
if (_file.EndsWith("xls") || _file.EndsWith("pdf") || _file.EndsWith("doc"))
return _file;
扩展是硬编码的,我需要将它们放在web.config中,并使其更具可配置性,它可以有1个允许的扩展,例如.doc或50个允许的扩展.doc、.xls、.xlsx、.ppt等
您有什么建议?首先将允许的扩展名放在app.config文件中。然后,您可以将它们加载到名为extensions的列表中,并使用如下代码:
if (extensions.Any(p => _file.EndsWith(p)))
return _file;
或者,如果_文件可以为空
if (extensions.Any(p => _file!= null && _file.EndsWith(p)))
return _file;
您可以将其存储在web.config文件中:
<appSettings>
<add key="AllowedExtensions" value=".xls,.pdf,.doc" />
</appSettings>
web.config:
<add key="allowed-extensions" value="pdf,jpg,doc" />
public static string Get(string Key)
{
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
KeyValueConfigurationCollection settings = config.AppSettings.Settings;
if (settings[Key] != null)
return settings[Key].Value;
else
return "";
}
现在,您的功能将是:
bool checkExt(string givenExtension){
string[] extensions = Get("alowed-extensions");
for(int i=0;i<extensions.length;i++)
if(extensions[i]==givenExtension) return true;
return false;
}
是否可以使用数据结构数组/列表来存储数据?如果是这样的话,那只是一个增量或操作。你也可以使用正则表达式,然后动态构建表达式。在我的智能手机中键入答案,sói最好明天将其格式化为+1,以便使用路径库实际获取文件扩展名。
bool checkExt(string givenExtension){
string[] extensions = Get("alowed-extensions");
for(int i=0;i<extensions.length;i++)
if(extensions[i]==givenExtension) return true;
return false;
}