gpt4 book ai didi

c# - HttpFileCollection 中的无效转换异常

转载 作者:行者123 更新时间:2023-11-30 13:34:48 25 4
gpt4 key购买 nike

我在下面有一个扩展方法,但是当我运行它时,foreach 给我 InvalidCastException 并且它说 *

Unable to cast object of type 'System.String' to type '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 说:

Clients encode files and transmit them in the content body using multipart MIME format with an HTTP Content-Type header of multipart/form-data. ASP.NET extracts the encoded file(s) from the content body into individual members of an HttpFileCollection. Methods and properties of the HttpPostedFile class provide access to the contents and properties of each file.

最佳答案

如果您查看此页面上的代码示例,它显示了您应该如何枚举集合,实际上,当您尝试按原样枚举时,您得到的是一个字符串。

http://msdn.microsoft.com/en-us/library/system.web.httpfilecollection.aspx

关于c# - HttpFileCollection 中的无效转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1905601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com