Excepción moldeada válida en HttpFileCollection
-
19-09-2019 - |
Pregunta
tengo a continuación un método de extensión, pero cuando corro esto, el foreach me da InvalidCastException
y dice *
No se puede convertir objeto de tipo 'System.String' para escribir '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;
}
Gracias de antemano.
MSDN Dice:
Los clientes codificar archivos y las transmiten en el contenido del cuerpo utilizando multiparte formato MIME con un tipo de contenido HTTP cabecera de multipart / form-data. ASP.NET extrae el archivo (s) codificada a partir de la cuerpo del contenido en miembros individuales de un HttpFileCollection. métodos y propiedades de la clase HttpPostedFile proporcionar acceso a los contenidos y propiedades de cada archivo.
Solución
Si nos fijamos en el ejemplo de código en esta página, que muestra cómo se debe enumerar la colección, usted es, de hecho, conseguir una cadena cuando intenta enumerar como eres.
http://msdn.microsoft.com/en- es / library / system.web.httpfilecollection.aspx
Otros consejos
El HttpFileCollection
empadronador colección vuelve llaves. Es necesario utilizar la llave en cada iteración del bucle para buscar el asociado objeto HttpPostedFile
. Así que el bucle tiene que tener este aspecto:
foreach (string name in collection) {
HttpPostedFile _file = collection[name];
// ...rest of your loop code...
}
Bueno, yo he encontrado una solución, pero parece tan estúpido, pero funciona.
Yo simplemente he cambiado el foreach
con éste:
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;
}
}