Exceção de elenco inválido no HttpFileCollection
-
19-09-2019 - |
Pergunta
Eu tenho um método de extensão a seguir, mas quando eu executo isso, o foreach me dá InvalidCastException
e diz *
Não é possível para objeto elenco de tipo 'System' para tipo 'System.Web.HttpPostedFile'.
Código:
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;
}
Agradecemos antecipadamente.
MSDN diz:
Os clientes codificar arquivos e transmiti-los no conteúdo do corpo usando multipart formato MIME com um HTTP Content-Type cabeçalho de várias partes / forma-dados. ASP.NET extractos o ficheiro codificado (s) a partir da corpo de conteúdo em membros individuais de um HttpFileCollection. métodos e propriedades da classe HttpPostedFile fornecer acesso ao conteúdo e propriedades de cada arquivo.
Solução
Se você olhar para o exemplo de código nesta página, ele mostra como você deve enumerar a coleção, você está de fato ficando uma corda quando você tenta enumerar como você é.
http://msdn.microsoft.com/en- us / library / system.web.httpfilecollection.aspx
Outras dicas
HttpFileCollection
coleção enumerador retorna chaves. Você precisa usar a chave em cada iteração do loop para procurar o associado objeto HttpPostedFile
. Assim, suas necessidades de loop para ficar assim:
foreach (string name in collection) {
HttpPostedFile _file = collection[name];
// ...rest of your loop code...
}
Bem, eu encontrei uma solução, mas parece tão estúpido, mas ele funciona.
Eu simplesmente mudou o foreach
com esta:
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;
}
}