Wednesday 24 July 2013

C# Get All Files from Folder and Subfolders and bind it in DropDownList in Asp.Net





Description:-                             



   In this Example we explain that how to Fetch List of File From the Directory that Direcory are available in our Website.

Here is a Function that will Fetch All List of File From our Cuurent Website or WebApplication are as Follow

public void ProcessFile(string path)

    {

        FileInfo fi = new FileInfo(path);

        if (Path.GetExtension(fi.Name).Equals(".aspx"))

        {

            DropDownList1.Items.Add(fi.Name);

            DropDownList2.Items.Add(fi.Name);

        }
}

in which Function we check that if File Extention is “.aspx” then and then it will be added to DropDownList. The path means we provide a string path of our Application It which they are Currentally Located.

To use this Example First you Have insert Following Namespace in your Class File like

using System.IO;
using System.Collections.Generic;

We all know that this is very useful when we have to search this File Name is Exist or Which Directory is Exist. My Real Experience when I was devloped the Website at that I have a Requirement to Calling a File a from List of File that are Available in Our Website as per Condition so at that time I was Devloped this Example and also you can use this Example for Doing this type of Solution.








Look at this above Image that Contain a Structure of the Website and Contain a List of File and Directory  that I have Fetch and Bind into the DropDownList in this Example are as show below.

to show Example of Bind Excelsheet Data to Gridview Export Excelsheet Data to Gridview 

Dynamically Create Rows Using DataTable and Bind to Gridview DataTable Example for binding data to Gridview 

Upload File and Bind to Gridview Upload File to Database and bind to Gridview
 


Source Code:-



<%@ Page Title="" Language="C#" MasterPageFile="~/Instructor.master" AutoEventWireup="true" CodeFile="addnotify.aspx.cs" Inherits="addnotify" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:Panel ID="Panel1" runat="server" Height="590px" Style="z-index: 102; left: 240px;
        position: absolute; top: 264px" Width="432px">
        &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
        &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;
        &nbsp;
        <asp:Label ID="Label1" runat="server" Font-Bold="True" ForeColor="RoyalBlue" Style="z-index: 100;
            left: 56px; position: absolute; top: 120px" Text="Notify Name"></asp:Label>
        <asp:Label ID="Label2" runat="server" Font-Bold="True" ForeColor="RoyalBlue" Style="z-index: 106;
            left: 64px; position: absolute; top: 184px" Text="File Name" Width="80px"></asp:Label>
           
            <asp:Label ID="Label3" runat="server" Font-Bold="True" ForeColor="RoyalBlue" Style="z-index: 106;
            left: 64px; position: absolute; top: 220px" Text="Target FileName" Width="100px"></asp:Label>
           
           
        <asp:TextBox ID="TextBox1" runat="server" Style="z-index: 102; left: 216px; position: absolute;
            top: 112px" TextMode="MultiLine" AutoPostBack="True"></asp:TextBox>
           
        <asp:Button ID="Button1" runat="server" Style="z-index: 103; left: 140px; position: absolute;
            top: 280px" Text="Add" Height="30px" Width="70px" OnClick="Button1_Click1"  />
        <asp:Button ID="Button2" runat="server" Style="z-index: 104; left: 265px; position: absolute;
            top: 280px" Text="Cancel" Height="30px" Width="70px" OnClick="Button2_Click" />
        <span style="font-size: 24pt; color: #006600; font-family: Monotype Corsiva; text-decoration: underline">
            Add Notification
            <asp:DropDownList ID="DropDownList1" runat="server" Style="z-index: 105; left: 216px; position: absolute;
                top: 176px">
            </asp:DropDownList>
            <asp:DropDownList ID="DropDownList2" runat="server" Style="z-index: 105; left: 216px; position: absolute;
                top: 230px">
            </asp:DropDownList>
        </span></asp:Panel>
       
        <br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Style="z-index: 105; left: 216px; position: absolute;
                top: 600px" DataKeyNames="id"
        BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
        CellPadding="3" CellSpacing="2" onrowdeleting="GridView1_RowDeleting">
        <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
    <Columns>
    <asp:TemplateField Visible="false">
   
    <ItemTemplate>
        <asp:Label ID="Label7" runat="server" Text='<%# Eval("id") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
   
    <asp:TemplateField>
   
    <ItemTemplate>
        <asp:Label ID="Label4" runat="server" Text='<%# Eval("name") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
   
    <ItemTemplate>
        <asp:Label ID="Label5" runat="server" Text='<%# Eval("filename") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
   
    <asp:TemplateField>
   
    <ItemTemplate>
        <asp:Label ID="Label6" runat="server" Text='<%# Eval("targetfnm") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
   
   
    <ItemTemplate>
        <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Delete">Delete</asp:LinkButton>
    </ItemTemplate>
    </asp:TemplateField>
   
    </Columns>
        <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
        <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
    </asp:GridView>
</asp:Content>


Code Behind:-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;
public partial class addnotify : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            grid();
            string path = MapPath(".");
            if (File.Exists(path))
            {
                // File path
                ProcessFile(path);
            }

            else if (Directory.Exists(path))
            {
                // This path is a directory

                ProcessDirectory(path);

            }
        }
    }
    public void grid()
    {
        SqlConnection con = new SqlConnection(@"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demoh;Password=Demo1@");
        string s1 = "select id,name,filename,targetfnm from notify";
        SqlCommand cmd = new SqlCommand(s1, con);
        con.Open();
        int j = cmd.ExecuteNonQuery();
        SqlDataAdapter sa = new SqlDataAdapter();
        DataTable dt = new DataTable();
        sa.SelectCommand = cmd;
        sa.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
       
    }
    protected void Button1_Click1(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demoh;Password=Demo1@");
        string s1 = "insert into notify(name,filename,targetfnm,date) values('" + TextBox1.Text + "','" + DropDownList1.SelectedValue + "','"+DropDownList2.SelectedValue+"',getdate())";
        SqlCommand cmd = new SqlCommand(s1, con);
        con.Open();
        int j = cmd.ExecuteNonQuery();
        if (j > 0)
            ClientScript.RegisterClientScriptBlock(this.GetType(), "fg", "<script> alert('added successfully'); </script>");
        grid();


    }
  
    public void ProcessDirectory(string targetDirectory)
    {
        // Process the list of files found in the directory.

        string[] fileEntries = Directory.GetFiles(targetDirectory);

        foreach (string fileName in fileEntries)

            ProcessFile(fileName);

        // Recurse into subdirectories of this directory.

        string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);

        foreach (string subdirectory in subdirectoryEntries)

            ProcessDirectory(subdirectory);

    }

    // Insert logic for processing found files here.

    public void ProcessFile(string path)
    {

        FileInfo fi = new FileInfo(path);
        if (Path.GetExtension(fi.Name).Equals(".aspx"))
        {
            DropDownList1.Items.Add(fi.Name);
            DropDownList2.Items.Add(fi.Name);
        }


    }
    protected void Button2_Click(object sender, EventArgs e)
    {

    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string id=GridView1.DataKeys[e.RowIndex].Value.ToString();
        SqlConnection con = new SqlConnection(@"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demoh;Password=Demo1@");
        string s1 = "delete from notify where id='" + id + "'";
        SqlCommand cmd = new SqlCommand(s1, con);
        con.Open();
        int j = cmd.ExecuteNonQuery();
        if (j > 0)
            ClientScript.RegisterClientScriptBlock(this.GetType(), "fg", "<script> alert('added successfully'); </script>");
       // GridView1.EditIndex = -1;
        grid();
       
    }
}

 



0 comments:

Post a Comment