Invalid Cast Exception in HttpFileCollection

Tarik picture Tarik · Dec 15, 2009 · Viewed 7.4k times · Source

I have an extension method below, but when I run this, the foreach gives me InvalidCastException and it says *

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

Thanks in advance.

MSDN Says :

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.

Answer

Jarrett Widman picture Jarrett Widman · Dec 15, 2009

If you look at the code sample on this page, it shows how you should enumerate the collection, you are in fact getting a string when you try to enumerate as you are.

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