【问题标题】:Count images in Folder using ASP.net使用 ASP.net 计算文件夹中的图像
【发布时间】:2013-04-24 17:21:17
【问题描述】:

我想计算一个文件夹文件夹的图像数量,但它会产生这个错误:

Could not find a part of the path 'c:\Content\slideshow\images\image\'.

所有图像都在项目的一个文件夹中。位于Content/slideshow/images/image

这是我的代码:

<%
  string dir = @"/Content/slideshow/images/image";
  string[] files;
  int numFiles;
  files = System.IO.Directory.GetFiles(dir);
  numFiles = files.Length;
  Response.Write("num ber of images :" + numFiles);
%>

【问题讨论】:

  • 为什么这被否决了?似乎是一个非常好的问题......

标签: asp.net-mvc


【解决方案1】:

"找不到路径的一部分 'c:\Content\slideshow\images\image\'"

很简单的意思是该文件夹不存在。如果您想使用相对路径,可以执行以下操作。

Server.MapPath("~/{RelativePathHere})

编辑:回应您的评论。您将需要遍历文件并检查每个文件的扩展名(保留您自己的计数)

【讨论】:

  • 太棒了!它工作皮诺。但它包括“Thumbs.db”,所以我们只能拍摄图像。谢谢。
【解决方案2】:

使用HttpContext.Current.Server.MapPath将虚拟路径映射到物理路径,然后传递给Directory.GetFiles方法

【讨论】:

    【解决方案3】:

    要调用 Directory.GetFiles(),您需要将完整路径传递给图像目录。

    string dirPath = @"~/Content/slideshow/images/image";
    string dirFullPath = Server.MapPath(dirPath);
    string[] files;
    int numFiles;
    files = System.IO.Directory.GetFiles(dirFullPath);
    numFiles = files.Length;
    Response.Write("number of images: " + numFiles);
    

    Server.MapPath 返回与 dirPath 虚拟路径关联的整个物理文件路径。

    【讨论】:

      【解决方案4】:

      您需要将此作为相对路径传递using Server.MapPath 然后我建议使用 DirectoryInfo.GetFiles 而不是 Directory.GetFiles 并过滤您想要的图像类型,这样您就不会计算非图像文件。这将产生一个FileInfo[]

      <%
        string dir = Server.MapPath(@"/Content/slideshow/images/image");
        FileInfo[] files;
        int numFiles;
        files = (new System.IO.DirectoryInfo(dir)).GetFiles("filePattern");
        numFiles = files.Length;
        Response.Write("num ber of images :" + numFiles);
      %>
      

      如果您要计算多种文件类型,最好的方法就是删除模式,然后过滤结果。

        var extensions = new String[] {"jpg", "png", "gif"};
        files = (new System.IO.DirectInfo(dir)).GetFiles();
      
        foreach(var extension in extensions)
        {
          numFiles += files.AsEnumerable.Where(f => f.Extension.Equals(extension));
        }
      

      【讨论】:

        【解决方案5】:
            int numberOfFiles ;
            string path = "C:/PIC";
            numberOfFiles = System.IO.Directory.GetFiles(path).Length;
        

        立即查看

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-28
          • 2012-10-07
          • 2016-10-15
          • 1970-01-01
          相关资源
          最近更新 更多