Invalid Cast Exception in HttpFileCollection

7.8k views Asked by At

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.

4

There are 4 answers

1
Jarrett Widman On BEST ANSWER

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

0
Tarik On

Well I've found a solution but it looks so stupid but it works.

I've simply changed the foreach with this one :

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;
                }
0
Atif Aziz On

The HttpFileCollection collection enumerator returns keys. You need to use the key in each iteration of the loop to look up the associated HttpPostedFile object. So your loop needs to look like this:

foreach (string name in collection) {
    HttpPostedFile _file = collection[name];
    // ...rest of your loop code...
}
1
Robin Kumar On
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;
    }
  }