开发者

Count images in Folder using ASP.net

开发者 https://www.devze.com 2023-04-05 11:57 出处:网络
I want to count the number of images a folder开发者_如何学运维 folder, but it produces this error :

I want to count the number of images a folder开发者_如何学运维 folder, but it produces this error :

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

All of the images are in a folder in the project. Located a Content/slideshow/images/image

This is my code:

<%
  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);
%>


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

Means very simply that the folder does not exist. If you want to user a relative path you can do the following.

Server.MapPath("~/{RelativePathHere})

Edit : In response to your comment. You will need to loop through the file and check for file extension of each (Keeping your own count)


Use HttpContext.Current.Server.MapPath to map the virtual path to physical path and then pass it to Directory.GetFiles method


To call Directory.GetFiles() you need to pass the full path to the images directory.

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 returns the entire physical file path associated to the dirPath virtual path.


You need to pass this as a relative path using Server.MapPath Then I would suggest using DirectoryInfo.GetFiles instead of Directory.GetFiles and filter on the image types that you want, so you don't count non-image files. This will yield a 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);
%>

If you have multiple file types that you want to count the best way to do this is just to remove the pattern then filter the results.

  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));
  }


    int numberOfFiles ;
    string path = "C:/PIC";
    numberOfFiles = System.IO.Directory.GetFiles(path).Length;

Check Now

0

精彩评论

暂无评论...
验证码 换一张
取 消