Thursday 22 May 2014

Get Filenames From Folder in Gridview Control in ASP.Net


Introduction
This article introduces the Directory class and shows how to get the file names from a folder into a GridView control.

Directory Class
The System.IO.Directory class in the .NET Framework class library provides static methods for creating, copying, moving, and deleting directories and subdirectories. For using the Directory class you need to use the System.IO namespace.

Directory.GetFiles method
The GetFiles method returns the names of files in a specified directory or returns a string array of file names.

protected void BindGridview()
    {
        string[] filesLoc = Directory.GetFiles(Server.MapPath("~/MyFiles/"));
        List<ListItem> files = new List<ListItem>();
        foreach (string file in filesLoc )
        {
            files.Add(new ListItem(Path.GetFileName(file)));
        }
        gvFiles.DataSource = files;
        gvFiles.DataBind();
    }

No comments:

Post a Comment