以下に拡張メソッドがありますが、これを実行すると、foreachInvalidCastException
で * と表示されます。
タイプ 'System.String' のオブジェクトをタイプ '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 のコメント:
クライアントはファイルをエンコードし、multipart/form-data の HTTP Content-Type ヘッダーを持つマルチパート MIME 形式を使用してコンテンツ本文で送信します。ASP.NET は、エンコードされたファイルをコンテンツ本文から HttpFileCollection の個々のメンバーに抽出します。HttpPostedFile クラスのメソッドとプロパティは、各ファイルのコンテンツとプロパティへのアクセスを提供します。