Pregunta

I have a MVC4 site (www.testsite.com/test) I also have a separate directory for storing downloadable files (www.testsite.com/downloads)

I have configured the downloads directory to be browsable in IIS.

How can I read the contents of the directory and generate a list of files in MVC?

I have read up on the DirectoryInfo GetFiles() method but It only works for local directories and the /Downloads directory is on a test server.

¿Fue útil?

Solución

First, create a Web.config value for the folder. Something like this:

<appSettings>
  <add key="DownloadsDirectory" value="C:\path\to\folder" />
</appSettings>

For any given instance of the application (local development instance, test server instance, production server instance, etc.) you'd update that instance's Web.config to specify the folder relevant to that instance. They don't all have to use the same folder, each can use whatever folder is appropriate. So your development machine doesn't need to access the production server's folder, just point it to some directory on your computer.

Second, use that value when reading from the directory. For example:

var fileNames = Directory.GetFiles(ConfigurationManager.AppSettings["DownloadsDirectory"]);

Naturally you'll want to check in code if ConfigurationManager.AppSettings["DownloadsDirectory"] has a value before trying to use it, and raise an error that the configuration is invalid if there's no value. You might even use Directory.Exists() with the value as another check, again raising a friendly error if it doesn't exist.

The main point is that if you want to get information on files in a directory, Directory or DirectoryInfo or lots of other objects in System.IO are pretty much what you'd use.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top