【发布时间】:2011-03-11 06:02:25
【问题描述】:
在对 ASP.Net (4.0) Request.Files(上传)集合进行一些基本验证时,我决定尝试使用 LINQ。
集合是IEnumerable<T>,因此不提供 ForEach。愚蠢地我决定建立一个可以完成这项工作的扩展方法。很抱歉说没有那么成功...
运行扩展方法(如下)引发下一个错误:
无法将“System.String”类型的对象转换为“System.Web.HttpPostedFile”类型
显然有些东西我没有得到,但我看不到它是什么,所以冒着看起来像个白痴的风险(不会是第一次)这里是 3 块代码,以及一个承诺感谢任何帮助。
一、带有Action参数的扩展方法:
//Extend ForEach to IEnumerated Files
public static IEnumerable<HttpPostedFileWrapper> ForEach<T>(this IEnumerable<HttpPostedFileWrapper> source, Action<HttpPostedFileWrapper> action)
{
//breaks on first 'item' init
foreach (HttpPostedFileWrapper item in source)
action(item);
return source;
}
当内部 foreach 循环命中 'source' 中的 'item' 时会发生错误。
这是调用代码(变量 MaxFileTries 和 attachPath 之前已正确设置):
var files = Request.Files.Cast<HttpPostedFile>()
.Select(file => new HttpPostedFileWrapper(file))
.Where(file => file.ContentLength > 0
&& file.ContentLength <= MaxFileSize
&& file.FileName.Length > 0)
.ForEach<HttpPostedFileWrapper>(f => f.SaveUpload(attachPath, MaxFileTries));
最后,Action 目标,保存上传文件 - 我们似乎从来没有到过这里,但以防万一,这里是:
public static HttpPostedFileWrapper SaveUpload(this HttpPostedFileWrapper f, string attachPath, int MaxFileTries)
{
// we can only upload the same file MaxTries times in one session
int tries = 0;
string saveName = f.FileName.Substring(f.FileName.LastIndexOf("\\") + 1); //strip any local
string path = attachPath + saveName;
while (File.Exists(path) && tries <= MaxFileTries)
{
tries++;
path = attachPath + " (" + tries.ToString() + ")" + saveName;
}
if (tries <= MaxFileTries)
{
if (!Directory.Exists(attachPath)) Directory.CreateDirectory(attachPath);
f.SaveAs(path);
}
return f;
}
我承认上面的一些内容是“发现的一些东西”的拼凑,所以我可能会得到我应得的,但如果有人对此有很好的理解(或至少经历过),也许我可以学习一些东西。
谢谢。
【问题讨论】:
-
好的,我试过这个:
Request.Files.Cast<HttpPostedFile>().Select(file => new HttpPostedFileWrapper(file)).Where( file => file.ContentLength > 0 && file.ContentLength <= MaxFileSize && file.FileName.Length > 0).ToList<HttpPostedFileWrapper>().ForEach(file=>file.SaveUpload(attachPath,MaxFileTries) );结果相同 -
为什么需要
ForEach<T>中的T?
标签: c# linq foreach extension-methods ienumerable