Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a directory

Tags:

c#

.net

asp.net

I'm stuck trying to figure out how to print out the images I'm storing in a directory in ASP/C#

I found this, but the problem is it prints out C:\\Visual Studios 2010\Projects\MyTestUploader\Files\img001.jpg

string[] fileEntries = Directory.GetFiles(sourceDir);
foreach (string fileName in fileEntries)
{
Label1.Text += "<img src=\"" + fileName + "" /><br />";
}

For now I just want to simply print out all the images in the directory. I'll worry about formatting them nicely, later :)

like image 292
sab669 Avatar asked Feb 04 '12 16:02

sab669


People also ask

How do I loop through a specific directory in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

How do I jump to a directory?

We'll use "cd" to move down as well as up the directory structure. The second way to list files in a directory, is to first move into the directory using the "cd" command (which stands for "change directory", then simply use the "ls" command.

How do you go to a directory in Linux?

Navigate directories. Open a window, double-click on a folder, and then double-click on a sub-folder. Use the Back button to backtrack. The cd (change directory) command moves you into a different directory.


1 Answers

You can use Path.GetFileName to get the file name and extension of the specified path, whilst excluding the directory path (which is presumably what you want).

string[] fileEntries = Directory.GetFiles(sourceDir);
foreach (string fileName in fileEntries)
{
    Label1.Text += "<img src=\"" + Path.GetFileName(fileName) + "\" /><br />";
}

For example, calling

Path.GetFileName(@"C:\Visual Studios 2010\Projects\MyTestUploader\Files\img001.jpg")

would return "img001.jpg".

Note that you were also missing a \ to escape the " at the end of your attribute value.

like image 157
Douglas Avatar answered Sep 28 '22 06:09

Douglas