简体   繁体   English

如何从Web应用程序外部的Web URL获取文件列表

[英]How to get list of files from web URL outside my web application

I am using ASP.NET 4.5 with C# . 我使用ASP.NET 4.5C#

I have created a web API that points to the folders out of my web-application to get some shared resources. 我创建了一个web API指向 我的Web应用程序中文件夹以获取一些共享资源。 Now, I want to retrieve the list of files from the directory to which the web-api call points. 现在,我想从web-api调用指向的目录中检索文件列表

For example, my web application is resides on my local hard-drive's F:\\Projects\\Web1 directory. 例如,我的Web应用程序驻留在我的本地硬盘驱动器的F:\\Projects\\Web1目录中。 I have placed some images in C:\\SharedRes\\images directory. 我在C:\\SharedRes\\images目录中放置了一些图像。 I have created a web-api that fetches images from this shared directory. 我创建了一个web-api ,从这个共享目录中获取图像。 For eg http://localhost/api/images/a.jpg will get the a.jpg from C:\\SharedRes\\images directory. 例如, http://localhost/api/images/a.jpg将从C:\\SharedRes\\images目录获取a.jpg It is working fine, but I want to get the list of files from C:\\SharedRes\\images whenever I make a call to web-api like http://localhost/api/images . 它运行正常,但每当我调用web-apihttp://localhost/api/images ,我想从C:\\SharedRes\\images获取文件列表

I have tried following : 我试过以下:

DirectoryInfo directoryInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("http://localhost/api/images"));
FileInfo[] file = directoryInfo.GetFiles().Where(f => f.Extension == (".bmp") || f.Extension == (".jpg") || f.Extension == (".png") || f.Extension == (".TIFF") || f.Extension == (".gif")).ToArray();

But it gives URI format not supported error. 但它给出了URI format not supported错误。

Please let me know if any solution. 如果有任何解决方案,请告诉我。

HttpServerUtility.MapPath method gets virtual path as parameter. HttpServerUtility.MapPath方法将虚拟路径作为参数。

You should use HttpContext.Current.Server.MapPath("/api/images") 你应该使用HttpContext.Current.Server.MapPath("/api/images")

You Can simply use Directory class with it's GetFiles method to do so. 您只需使用Directory类及其GetFiles方法即可。 The following code is for getting all files in C:\\SharedRes\\images\\ directory: 以下代码用于获取C:\\SharedRes\\images\\目录中的所有文件:

string[] _Files = Directory.GetFiles(@"C:\SharedRes\images\");
if (_Files != null && _Files.Count() > 0)
{ 
  FileInfo _file;
  string   _fileName="";

  foreach (string file in _Files)
  {
       _file = new FileInfo(file);
       _fileName = _fileName + @"<br/>" + _file.Name;
  }

Response.Write(_fileName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM