在HttpFileCollection无效的转换异常
-
19-09-2019 - |
题
下面我有一个扩展方法,但是当我运行此,在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表示:强>
客户端编码的文件和发送它们 在内容机身采用多 MIME格式与HTTP内容类型 多部分/格式数据的报头中。 ASP.NET 提取从编码后的文件(多个) 内容主体为个人会员 的HttpFileCollection。方法和 所述HttpPostedFile类的属性 提供对内容和 每个文件的属性。
解决方案
如果你看看这个页面上的代码示例,它表明你应该如何枚举集合,你实际上得到一个字符串,当您试图枚举的你。
http://msdn.microsoft.com/en-我们/库/ system.web.httpfilecollection.aspx
其他提示
在 HttpFileCollection
收集枚举返回键。您需要使用在每次循环的关键,查找相关的 HttpPostedFile
对象。所以,你的循环需要是这样的:
foreach (string name in collection) {
HttpPostedFile _file = collection[name];
// ...rest of your loop code...
}
好吧,我已经找到了解决方案,但它看起来如此愚蠢,但它的工作原理。
我已经简单地改变了foreach
与这一个:
foreach (string fileString in collection.AllKeys) {
HttpPostedFile _file = collection[fileString];
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;
}
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string _fileSavePath = _DocPhysicalPath + "_" + hpf.FileName;
}
}
不隶属于 StackOverflow