Invalid Cast exception in HttpFileCollection

I have an extension method below, but when I run it, foreach gives me InvalidCastExceptionand it says *

Unable to start object of type 'System.String' to enter type 'System.Web.HttpPostedFile'.

The 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 transfer them in the content body using multipart. MIME format with the content type HTTP header multipart / form-data. ASP.NET extracts the encoded file from the contents of the body into individual members of the HttpFileCollection. The methods and properties of the HttpPostedFile class provide access to the contents and properties of each file.

+3
source share
4 answers

HttpFileCollection . HttpPostedFile. :

foreach (string name in collection) {
    HttpPostedFile _file = collection[name];
    // ...rest of your loop code...
}
+3

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

I just changed foreachto this:

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;
                }
+1
source
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;
    }
  }
0
source

Source: https://habr.com/ru/post/1725691/


All Articles