简体   繁体   中英

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

I am using ASP.NET 4.5 with C# .

I have created a web API that points to the folders out of my web-application to get some shared resources. Now, I want to retrieve the list of files from the directory to which the web-api call points.

For example, my web application is resides on my local hard-drive's F:\\Projects\\Web1 directory. I have placed some images in C:\\SharedRes\\images directory. I have created a web-api that fetches images from this shared directory. For eg http://localhost/api/images/a.jpg will get the a.jpg from C:\\SharedRes\\images directory. 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 .

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.

Please let me know if any solution.

HttpServerUtility.MapPath method gets virtual path as parameter.

You should use HttpContext.Current.Server.MapPath("/api/images")

You Can simply use Directory class with it's GetFiles method to do so. The following code is for getting all files in C:\\SharedRes\\images\\ directory:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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