Question

I am creating a website using asp.net and c#
I need to access all files one by one in a directory. So I wrote the following code.

    string[] ssImgs = Directory.GetFiles("images/movies");
    Label1.Text = ssImgs[0];
    Label2.Text = ssImgs[1];

But it gives an error. What is the correct way to do this? Thanks in advance.

Was it helpful?

Solution

A little advice, when using the file system in ASP.NET, leverage Server.MapPath:

string[] ssImgs = Directory.GetFiles(Server.MapPath("~/images/movies"));

where ~/images/movies is the full relative path from the root of the web application.

Secondly, before just grabbing an index of the array, make sure it's actually there. It would be better to change your indexing code to something like this:

Label1.Text = ssImgs.Length >= 1 ? ssImgs[0] : "File 1 not found.";
Label2.Text = ssImgs.Length >= 2 ? ssImgs[1] : "File 2 not found.";

By making these two changes you won't have to worry about getting a DirectoryNotFound exception or an IndexOutOfRange exception.

OTHER TIPS

There are two potential issues here.

  1. If you doing have using System.IO; in your file, the Directory class will not be found by the compiler.

  2. The way you're specifying your path ("images/movies") will be relative to the current working directory, which is likely not the proper directory. You should use Server.MapPath or the Path class to build a full path to the proper folder, so you can specify the correct folder with a full, absolute path.

I got the correct way. It is

    string[] ssImgs = Directory.GetFiles(Server.MapPath("images/movies"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top