Monday, March 24, 2014

Get all files from directory in C# and ASP.NET

Here I am giving an example of How to get all files from directory in C#

Example:1 Get All files from directory and then display in Grid view.

A- drag a grid view control on .aspx page.

    <asp:GridView ID="GridView1" runat="server" BackColor="White" 
        BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" 
        CellSpacing="1" GridLines="None">
        <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
        <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
        <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
        <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
        <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
        <SortedAscendingCellStyle BackColor="#F1F1F1" />
        <SortedAscendingHeaderStyle BackColor="#594B9C" />
        <SortedDescendingCellStyle BackColor="#CAC9C9" />
        <SortedDescendingHeaderStyle BackColor="#33276A" />
    </asp:GridView>

B-  Add below code at Page_Load event of .aspx.cs file, Also add "using System.IO" Namespace in code behind file.

 protected void Page_Load(object sender, EventArgs e)
    {
        if(!this.IsPostBack)
        BindFiles();
    }

    protected void BindFiles()
    {
        try
        {
            string[] filePath = Directory.GetFiles(@"D:\myWebTest\Files\");

            GridView1.DataSource = filePath;
            GridView1.DataBind();
        }
        catch (Exception)
        {
            throw;
        }        
    }

C- Run your project and see result


















Example:2  Get or Search files with specified extension from directory in C#

A- Here is the .aspx.cs file code, I am here searching and displaying .jpg files

protected void Page_Load(object sender, EventArgs e)
    {
        if(!this.IsPostBack)
        BindFiles();
    }

    protected void BindFiles()
    {
        try
        {
            // Get only .jpg files
            string[] filePath = Directory.GetFiles(@"D:\myWebTest\Files\", "*.jpg");

            GridView1.DataSource = filePath;
            GridView1.DataBind();
        }
        catch (Exception)
        {
            throw;
        }        
    }


B- Run your project and see result...














If you want to search files inside sub folders then use SearchOption.AllDirectories in above code...

// Get only .jpg files including inside Sub Folders
  string[] filePath = Directory.GetFiles(@"D:\myWebTest\Files\", "*.jpg", SearchOption.AllDirectories);

---
Thats it

No comments:

Post a Comment

SharePoint Deployment Error : The specified path, file name, or both are too long.

Hi, Sometimes we get surprised with below error while deploying wsp file... Solution : To overcome with this issue, we just ne...