簡體   English   中英

如何顯示目錄(文件夾)中的所有文件

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

我想在listbox顯示所有圖片名稱。 我試圖弄清楚如何檢索文件名。 我試過了

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();
}

但是標簽中的結果如下所示:

http://localhost:49170/UBOimages
C:\Users\John\Documents\UBO\uboWebCustomer\HuronWood\HuronWood\UBOimages

並且當加載到服務器上時,此頁面將顯示錯誤,因為它不喜歡dirInfo路徑。 從文件夾(例如圖像文件夾)檢索所有文件的正確方法是什么

    DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("~/UBOimages"));
    FileInfo[] fileInfo = dirInfo.GetFiles("*.*", SearchOption.AllDirectories); 

循環瀏覽此fileinfo數組或將其綁定到任何Gridview或listview。

如果您需要獲取名為“ Data”的文件夾中的所有文件,只需將其編碼如下

 string[] Documents = System.IO.Directory.GetFiles("../../Data/");

現在,“文檔”由文件夾“數據”中文件的完整對象名稱組成。

System.IO.DirectoryInfo.GetFiles將幫助您獲取給定目錄的所有文件。

DirectoryInfo.ToString不能用於列出目錄文件。 它將給出當前DirectoryInfo對象的字符串表示形式,您會看到在這種情況下它是目錄路徑。

@我正在使用以上答案根據您的問題編寫我的代碼!!!

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);
        }

希望這可以幫助!!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM