简体   繁体   中英

How to display all the files from a directory (folder)

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)

    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.

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'.

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.

@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!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM