程序集 System.Core.dll中的System.Linq命名空间添加了许多扩展方法,看到
public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)
使用这个方法去除文件名中的非法字符,一行代码就可以搞定。
用Reflector查看一下源码:
public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (func == null)
{
throw Error.ArgumentNull("func");
}
TAccumulate local = seed;
foreach (TSource local2 in source)
{
local = func(local, local2);
}
return local;
}
实际使用:
private static readonly char[] InvalidFileNameChars = new[]
{
'"',
'<',
'>',
'|',
'\0',
'\u0001',
'\a',
'\b',
':',
'*',
'?',
'\\',
'/'
};
static void Main(string[] args)
{
}
public static string CleanInvalidFileName(string fileName)
{
//...
fileName = InvalidFileNameChars.Aggregate(fileName, (current, c) => current.Replace(c + "", ""));
//...
return fileName;
}
使用Lambda表达式可以使代码看起来更简洁。