httpfilecollection에서 잘못된 캐스트 예외
-
19-09-2019 - |
문제
아래에 확장 방법이 있지만, 이것을 실행할 때, Foreach는 나에게 제공합니다. InvalidCastException
그리고 그것은 *
'System.String'type 'system.web.httppostedFile'의 유형을 캐스트 할 수 없습니다.
코드 :
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;
}
미리 감사드립니다.
MSDN 말 :
클라이언트는 HTTP 컨텐츠 유형 헤더가 멀티 파트/양식 데이터 헤더를 사용하여 파일을 인코딩하고 컨텐츠 본문에서 전송합니다. ASP.NET는 인코딩 된 파일을 컨텐츠 본문에서 httpFileCollection의 개별 구성원으로 추출합니다. httppostedfile 클래스의 메소드 및 속성은 각 파일의 내용 및 속성에 대한 액세스를 제공합니다.
해결책
이 페이지의 코드 샘플을 보면 컬렉션을 열거 해야하는 방법을 보여줍니다. 실제로 열거하려고 할 때 문자열을 받고 있습니다.
http://msdn.microsoft.com/en-us/library/system.web.httpfilecollection.aspx
다른 팁
그만큼 HttpFileCollection
수집 열거자가 키를 반환합니다. 연관된 것을 찾으려면 루프의 각 반복에 키를 사용해야합니다. HttpPostedFile
물체. 따라서 루프는 다음과 같이 보일 필요가 있습니다.
foreach (string name in collection) {
HttpPostedFile _file = collection[name];
// ...rest of your loop code...
}
글쎄, 나는 해결책을 찾았지만 너무 바보처럼 보이지만 작동합니다.
나는 단순히 foreach
이것으로 :
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;
}
}
제휴하지 않습니다 StackOverflow