Reputation: 11609
I want to display all of my pictures names in a listbox
. I'm trying to figure out how to retrieve the file names.
I tried this
protected void Page_Load(object sender, EventArgs e)
{
string u = Request.Url.AbsoluteUri.ToString();
string serverPath = u.Substring(0, u.LastIndexOf("/")) + "/UBOimages";
Label1.Text = serverPath;
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("~/UBOimages"));
//FileInfo[] fileInfo = dirInfo.GetFiles();
Label2.Text = dirInfo.ToString();
}
But the results in the labels looks like this:
http://localhost:49170/UBOimages
C:\Users\John\Documents\UBO\uboWebCustomer\HuronWood\HuronWood\UBOimages
and when loaded on the server this page will give an error as it does not like the dirInfo path. What is the correct way to retrieve all the files from a folder (such as the image folder)
Upvotes: 0
Views: 1835
Reputation: 11609
@I am using the above answers to write my code according to your problem!!!
Using System.IO
protected void ListFiles()
{
const string MY_DIRECTORY = "/MyDirectory/";
string strFile = null;
foreach (string s in Directory.GetFiles(Server.MapPath(MY_DIRECTORY), "*.*")) {
strFile = s.Substring(s.LastIndexOf("\\") + 1);
ListBox1.Items.Add(strFile);
}
Hope this helps!!!
Upvotes: 0
Reputation: 47968
System.IO.DirectoryInfo.GetFiles
will help you get all files for a given directory.
DirectoryInfo.ToString
is not intended to be used to list directory files. It will give a string representation of the current DirectoryInfo
object and you see that in this case it's the directory path.
Upvotes: 1
Reputation: 1371
If you need to get all the files in the folder named 'Data', just code it as below
string[] Documents = System.IO.Directory.GetFiles("../../Data/");
Now the 'Documents' consists of array of complete object name of files in the folder 'Data'.
Upvotes: 1
Reputation: 475
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("~/UBOimages"));
FileInfo[] fileInfo = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);
Loop through this fileinfo array or bind it to any Gridview or listview.
Upvotes: 3