ASP.NET - how to show files and folders with delete option in gridview asp.net

Asked By mani on 06-Feb-12 01:29 AM
hi..i have folder with name  called 'flashfile'

and i will have so many subfolders in this..and how can i show this sub folders from flashfile to  gridview with delete option ??
and i have to show all folders to users..and delete option only for admin also??
any help????
smr replied to mani on 06-Feb-12 01:34 AM
hi

try this

http://msdn.microsoft.com/en-us/library/ms972940.gridview_fig36l%28l=en-us%29.gif

refer
http://msdn.microsoft.com/en-us/library/ms972940.aspx
D Company replied to mani on 06-Feb-12 01:44 AM
Hello Friend.

I think you have two requirement.

1. u want to delete subfolder, for that you can try previous solution , and let me know if it not feasible.
2.second u want to make visible(delete button) only for specific user(Admin).here you can do this in gridview rowdata bound event

 if (e.Row.RowType == DataControlRowType.DataRow)
   
{

//you can use your own logic to get logged in user name, here i hope that you have used DB to do this and i suppose that you can get that user name easily, let me in case more help on this
     
if (user=="Admin")
              e
.Row.Cells[0].Controls[0].Visible = true;
       
else
         e
.Row.Cells[0].Controls[0].Visible = false;

     
}


Regards
D
Web Star replied to mani on 06-Feb-12 01:47 AM
if you want to do operation with folder and file than first use System.IO namespace on you page and than with the help of that you can read folder, subfolder and file of specified path and display it as you want in gridview .
the sample code with good example is here
http://www.4guysfromrolla.com/articles/090110-1.aspx 

And you want to delete option in gridview than just put one delete column in gridview and than write the code for delete event of gridview simply only the matter is you should handle delete operation properly in that event mean if selection for file than simply do delete opertion with System.IO namespace if selection is folder than you make sure first delete all file form that folder than delete folder if folder having subfolder than all subfolder should be deleted first than you delete parent folder in you code.
dipa ahuja replied to mani on 06-Feb-12 02:05 AM

<ItemTemplate>

 <asp:Label ID="lblFile" runat="server" Text='<%# Eval("Filename") %>'></asp:Label>

 <asp:LinkButton ID="linkButton1" CommandName="Delete" runat="server" Text="Delete" />

</ItemTemplate>

 

and Implement the RowCommand Event:

 

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

{

  if (e.CommandName == "Delete")

  {

    /* DELETE FROM DATABASE */

 

    GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);

    string fileName = ((Label)row.FindControl("lblFile")).Text;

    // Code to fire Delete with query "DELETE from table1 where url=fileName

 

    /* DELETE FROM DIRECTORY */

 

    string path = Server.MapPath("~/Docs/") + fileName;

 

    System.IO.Directory.Delete(path, true);

  }

}

mani replied to dipa ahuja on 06-Feb-12 02:27 AM
hi i used liket this..please help me..i can display all folders using this code..but i am not able to delete folders using this..
any help???


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"  AllowPaging="True"
                            onrowcommand="GridView1_RowCommand"
                            onrowdatabound="GridView1_RowDataBound"
                            onpageindexchanged="GridView1_PageIndexChanged"
                            onpageindexchanging="GridView1_PageIndexChanging" PageSize="4"
                            onrowdeleting="GridView1_RowDeleting">
                            <PagerSettings FirstPageText="First" LastPageText="Last"
                            Mode="NumericFirstLast" NextPageText="Next" PageButtonCount="35"
                            PreviousPageText="Prev"/>
                         <Columns>
                         <asp:TemplateField>
                          <HeaderTemplate>
                               <table border="0" cellpadding="0" cellspacing="0" width="800px" style="background-color:#D3E7F5;">
                                  <tr>                                
                                    <td style="border-bottom:1px solid #053766; height:40px;" id="HideTitle" runat="server">
                                      <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                        <tr>
                                          <td align="left" style="padding:3px; padding-left:10px;">
                                            <asp:LinkButton ID="lnkBack" CssClass="Download" runat="server"  CommandName="Back"></asp:LinkButton>
                                          </td>
                                        </tr>
                                      </table>
                                    </td>
                                  </tr>
                               </table>                                
                              </HeaderTemplate>
                              <ItemTemplate>
                                <table border="0" cellpadding="0" cellspacing="0" width="800px" style="background-color:#D3E7F5;">
                                  <tr>                                
                                    <td  style="border-bottom:1px solid #053766;">
                                      <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                       <tr>
                                          <td>
                                            <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                             <tr>
                                                <td align="center" style="width:50px; padding:3px; border-right:1px solid #053766;">
                                                  <img src="images/Folder-icon.png" alt="" />
                                                </td>
                                                <td align="left" style="padding:3px; padding-left:10px;">
                                                  <asp:LinkButton ID="lnkFolder" CssClass="Download" runat="server" Text='<%# Eval("Name") %>'
                                                    CommandName="Select"></asp:LinkButton>
                                                 <td>
                                                <asp:LinkButton ID="LinkButton1" runat="server" Text="Delete" CommandArgument='<%# Eval("Path") +"," +  Eval("Type")%>'
                                                  CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete?')"></asp:LinkButton>
                                               </td>

                                                </td>
                                              </tr>
                                            </table>
                                          </td>
                                       </tr>                                       
                                      </table>
                                    </td>
                                  </tr>
                                </table>
                              </ItemTemplate>
                         </asp:TemplateField>
                         </Columns>
                         </asp:GridView>



   protected void Page_Load(object sender, EventArgs e)
    {
      
        
          RootPath = "~/flashfile";
          FillFileAndFolders(RootPath);
       
       
      
    }
    private string RootPath
    {
      get
      {
        if (ViewState["RootPath"] != null)
        {
          return ViewState["RootPath"].ToString();
        }
        else
        {
          return string.Empty;
        }
      }
      set
      {
        ViewState["RootPath"] = value;
      }
    }
    private string ExistingPath
    {
      get
      {
        if (ViewState["ExistingPath"] != null)
        {
          return ViewState["ExistingPath"].ToString();
        }
        else
        {
          return string.Empty;
        }
      }
      set
      {
        ViewState["ExistingPath"] = value;
      }
    }

    private void FillFileAndFolders(string virtualDirPath)
    {
      DataTable filesAndFolders = new DataTable();
      filesAndFolders.Columns.Add("Name");
      filesAndFolders.Columns.Add("Path");
      filesAndFolders.Columns.Add("Type");

      string rootPath = Server.MapPath(virtualDirPath);
      if (Directory.Exists(rootPath))
      {
        string[] Directories = Directory.GetDirectories(rootPath);
        for (int i = 0; i < Directories.Length; i++)
        {
          DirectoryInfo drinfo = new DirectoryInfo(Directories[i]);
          DataRow dr = filesAndFolders.NewRow();
          dr["Name"] = drinfo.Name;
          dr["Path"] = drinfo.FullName;
          dr["Type"] = "D";
          filesAndFolders.Rows.Add(dr);
        }
        string[] files = Directory.GetFiles(rootPath);
        for (int i = 0; i < files.Length; i++)
        {
          FileInfo fInfo = new FileInfo(files[i]);
          DataRow dr = filesAndFolders.NewRow();
          dr["Name"] = fInfo.Name;
          dr["Path"] = fInfo.FullName;
          dr["Type"] = "F";
          filesAndFolders.Rows.Add(dr);
        }
      }
    
     GridView1.DataSource = filesAndFolders;
     GridView1.DataBind();
    }
    
    private string MapUrl(string physicalPath)
    {
      string appPath = Server.MapPath(RootPath);
      string url = String.Format(RootPath + "{0}", physicalPath.Replace(appPath, "").Replace("\\", "/"));
      return url;
    }

  protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
      string commanName = e.CommandName.ToString();
      string[] values = e.CommandArgument.ToString().Split(',');
      GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
      LinkButton lblProdId = (LinkButton)row.FindControl("lnkFolder");
      string ss = lblProdId.Text;
      if (commanName.Equals("Select"))
      {
        if (values[1].Equals("F"))
        {
          //Now,since you need the DOWNLOAD dialog to appear
          HttpContext.Current.Response.ContentType = "application/octet-stream";
          HttpContext.Current.Response.AddHeader("Content-Disposition",
          "attachment; filename=" + Path.GetFileName(values[0]));
          HttpContext.Current.Response.Clear();
          HttpContext.Current.Response.WriteFile(values[0]);
          HttpContext.Current.Response.End();
        }
        else
        {
          ExistingPath = MapUrl(values[0]).Replace(RootPath, "..");
          FillFileAndFolders(MapUrl(values[0]));
        }
      }

      else if (commanName.Equals("Delete"))
      {
        if (values[1].Equals("F"))
        {
          File.Delete(values[0]);
        }
        else
        {
          Directory.Delete(values[0]);
        }
        string path = ExistingPath;
        if (path != null)
        {
          if (path.Contains(".."))
          {
            path = path.Replace("..", RootPath);
            ExistingPath = path;
          }
          FillFileAndFolders(path);
        }
        else
        {
          FillFileAndFolders(RootPath);
        }
      }
      else if (commanName.Equals("Edit"))
      {
        //show a popup or the dialog where  user can rename the folder or the file;
      }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

      if (e.Row.RowType == DataControlRowType.Header)
      {
        LinkButton lnkBack = e.Row.FindControl("lnkBack") as LinkButton;
        lnkBack.CommandName = "Back";
        lnkBack.CommandArgument = ExistingPath;
        lnkBack.Text = ExistingPath;
      }
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
        LinkButton lnkFolder = e.Row.FindControl("lnkFolder") as LinkButton;
        string type = ((System.Data.DataRowView)(e.Row.DataItem)).Row["Type"].ToString();
        lnkFolder.CommandName = "Select";
        lnkFolder.CommandArgument = ((System.Data.DataRowView)(e.Row.DataItem)).Row["Path"].ToString() + "," + type;
      }

    }