【发布时间】:2010-12-26 17:02:53
【问题描述】:
我在下面有一个扩展方法,但是当我运行它时,foreach 给了我InvalidCastException,它说 *
无法转换类型的对象 'System.String' 键入 'System.Web.HttpPostedFile'。
代码:
public static List<Attachment> GetFiles(this HttpFileCollection collection) {
if (collection.Count > 0) {
List<Attachment> items = new List<Attachment>();
foreach (HttpPostedFile _file in collection) {
if (_file.ContentLength > 0)
items.Add(new Attachment()
{
ContentType = _file.ContentType,
Name = _file.FileName.LastIndexOf('\\') > 0 ? _file.FileName.Substring(_file.FileName.LastIndexOf('\\') + 1) : _file.FileName,
Size = _file.ContentLength / 1024,
FileContent = new Binary(new BinaryReader(_file.InputStream).ReadBytes((int)_file.InputStream.Length))
});
else
continue;
}
return items;
} else
return null;
}
提前致谢。
MSDN 说:
客户端对文件进行编码并传输它们 在内容正文中使用多部分 带有 HTTP Content-Type 的 MIME 格式 多部分/表单数据的标题。 ASP.NET 从 内容主体转化为单个成员 一个 HttpFileCollection。方法和 HttpPostedFile 类的属性 提供对内容的访问和 每个文件的属性。
【问题讨论】:
-
在给定的代码中在哪一行抛出此错误
-
@solairaja,当它第一次点击
foreach (HttpPostedFile _file in collection)代码行时,它给出了错误。
标签: c# asp.net httppostedfile httpfilecollection