当发现没有空文件抛出时,此代码不起作用


foreach (System.Web.HttpPostedFile f in Request.Files)
{
   if (f.ContentLength > 0 && f.FileName.EndsWith(".pdf"))
   {
      //work done here
   }
}

我也测试了Request.Files数组中的每个项目,可以在 Debug模式下按如下方式手动转换(每个索引)
?(System.Web.HttpPostedFile)Request.Files[index]
{System.Web.HttpPostedFile}
    ContentLength: 536073
    ContentType: "application/pdf"
    FileName: "E:\\2.pdf"
    InputStream: {System.Web.HttpInputStream}

但是,以下代码有效
for (index = 0; index < Request.Files.Count; index++)
{
   System.Web.HttpPostedFile f = Request.Files[index];
   if (f.ContentLength > 0 && f.FileName.EndsWith(".pdf"))
   {
      //work done here
   }
}

知道出了什么问题吗?谢谢

最佳答案

Request.FilesHttpFileCollection,又是NameObjectCollectionBase。这不是很明显,但是它的GetEnumerator()产生集合的键-而不是项目本身。所以:

foreach(string key in Request.Files) {
    // fetch by key:
    var file = Request.Files[key];

    // ....
}

这并不明显,尤其是因为该集合是非通用的IEnumerable而不是IEnumerable<string>

它是at least documented:



但是:您认为Files上的迭代会给您文件对象,对您来说不是是不合理的。

关于c# - foreach循环无法强制转换,但需要手动进行强制转换和for循环工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14774109/

10-09 06:40
查看更多