How to list all files from a server directory in ASP.NET MVC?

Asked

Viewed 2,031 times

1

I want to know how to create a List<string> with the filenames of a given directory.

The service is hosted on a shared server, published in my httpdocs.

I have several images inside httpdocs/img/imagens.

How do I access this directory?

Code of the Controler:

DirectoryInfo diretorio = new DirectoryInfo("~/img/imagens/");
FileInfo[] arquivos = diretorio.GetFiles();

Error:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
    Could not find a part of the path 'C:\Windows\SysWOW64\inetsrv\~\img\imagens'.
</string>

1 answer

2


That’s almost it. Switch to:

DirectoryInfo diretorio = new DirectoryInfo(Server.MapPath("~/img/imagens/"));
FileInfo[] arquivos = diretorio.GetFiles();

See more here.

  • 1

    To complete, Server.MapPath stays inside HttpContext.Current, then always use HttpContext.Current.Server.MapPath or do the using

Browser other questions tagged

You are not signed in. Login or sign up in order to post.