Ongeldig Cast Uitsondering in HttpFileCollection
-
19-09-2019 - |
Vra
Ek het 'n uitbreiding metode hieronder, maar toe ek dit uit te voer, die foreach gee my InvalidCastException
en dit sê *
Kan cast voorwerp van tipe 'System.String' tipe 'System.Web.HttpPostedFile.
Code:
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;
}
Dankie by voorbaat.
MSDN Sê:
Kliënte enkodeer lêers en stuur hulle in die inhoud liggaam met behulp van multipart MIME-formaat met 'n HTTP Content-Type kop van multipart / form-data. ASP.NET uittreksels die geënkodeerde lêer (s) van die inhoud liggaam in individuele lede van 'n HttpFileCollection. metodes en eienskappe van die HttpPostedFile klas bied toegang tot die inhoud en eienskappe van elke lêer.
Oplossing
As jy kyk na die kode monster op hierdie bladsy, dit toon hoe jy die versameling moet opsom, jy is in werklikheid om 'n string wanneer jy probeer om te noem as jy is.
http://msdn.microsoft.com/en- ons / library / system.web.httpfilecollection.aspx
Ander wenke
Die HttpFileCollection
versameling opnemer opbrengste sleutels. Wat jy nodig het om die sleutel in elke iterasie van die lus te gebruik om te soek na die verband HttpPostedFile
voorwerp. So jou lus behoeftes om te lyk soos hierdie:
foreach (string name in collection) {
HttpPostedFile _file = collection[name];
// ...rest of your loop code...
}
Wel, ek het gevind dat 'n oplossing, maar dit lyk so dom, maar dit werk.
Ek het net verander die foreach
met hierdie een:
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;
}
}