Access Virtual Directory folder through code behind Asp.net

北城余情 提交于 2020-01-01 12:10:03

问题


I am trying to access a Virtual Directory folder from Code-behind.

  • ASP.Net Website Name : SuperImages
  • Physical folder : C:\images
  • Virtual Directory folder : allimages (In same level as App_Data, Scripts, Properties folders)

I am trying to access and do a count of the number of items in this folder, then display them on a webpage.

How should I do this?

Thanks in advance!

=======================================================================

Update : From the posts below, it seems that Server.MapPath would give me the correct physical path. However, it seems to me that I am getting the wrong physical path. Reason should be I am running 'debug' mode.

Hence, any idea how I can ensure Server.MapPath point correctly and while running in debug mode?

======================================================================

SOLUTION :

Problem was that on Debug mode, I was using the VS Dev Server instead of my local IIS. I re-created a Virtual Directory for my app in the local IIS. Re-created another virtual directory for the 'allimages' folder in this newly created app, and it solved the problem.


回答1:


You can do it this way:

DirectoryInfo dir= new DirectoryInfo(Server.MapPath("/allimages"));

Then you can get the Files in this folder as below:

FileInfo[] files = dir.GetFiles(string searchPattern,SearchOption searchOption);

and for tha count of files you can simply do array count.




回答2:


AS suggested in the post
File count from a folder
You can go like this.

You can use the

Directory.GetFiles method

Also see Directory.GetFiles Method (String, String, SearchOption)

You can specify the search option in this overload.

TopDirectoryOnly: Includes only the current directory in a search.

AllDirectories: Includes the current directory and all the subdirectories in a search operation. This option includes reparse points like mounted drives and symbolic links in the search.

// searches current directory and sub directory
int fCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length;
// searches current directory
int fCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectory).Length;

You will have to use Server.MapPath for your virtual directory folder.

  string dir = Server.MapPath(@"/Content/slideshow/images/image");
  FileInfo[] files;
  int numFiles;
  files = (new System.IO.DirectoryInfo(dir)).GetFiles("filePattern");
  numFiles = files.Length;



回答3:


You can access it in the same way you'd access it from a normal application. I,d use the Directory class to get a count of the items. Just make sure you have enough permissions.

Directory.EnumerateFiles(myPath).Length;


来源:https://stackoverflow.com/questions/15320967/access-virtual-directory-folder-through-code-behind-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!