HttpFileCollection での無効なキャスト例外
-
19-09-2019 - |
質問
以下に拡張メソッドがありますが、これを実行すると、foreach が表示されます。 InvalidCastException
そしてそれは*と言う
タイプ「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コンテンツタイプのヘッダーを使用してMultiPart Mime形式を使用してコンテンツボディに送信します。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