Click here to Skip to main content
15,896,063 members

Using a Gridview to display File Directory contents

pmcm asked:

Open original thread
Hi I need some advice/help with my expandable Gridview. I am trying to map the contents of "c:\inetpub" to a gridview. I have been debugging my code and can see rows being added to my DataTable gvSource but whenever I bind this DT to the Gridview I get the following error:
"Object reference not set to an instance of an object. at gvFiles_RowDataBound(Object sender, GridViewRowEventArgs e)" in particular this line:
C#
var item = e.Row.DataItem as FileSystemItemCS;
item is being set to null

I'll include my code so far:
front end Control code
ASP.NET
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="BrowseFilesUsrCtrl.ascx.cs" Inherits="SrvViewingTool.Controls.BrowseFilesUsrCtrl" %>

<table width="100%">
    <tr>
        <td style="width: 631px; removed: static; removed 10px; height: 16px" valign="top">
            <asp:Label ID="lblDateMod" runat="server" EnableViewState="False" Font-Bold="False" Font-Names="Arial Narrow"
                Font-Size="Smaller"></asp:Label></td>
        <td style="width: 1604px; removed: static; height: 16px" valign="top" colspan="2">
            <asp:Label ID="lblFile" runat="server" Font-Bold="False" Font-Names="Arial Narrow" Font-Size="Smaller" EnableViewState="False"></asp:Label></td>
    </tr>
    <tr>
        <td style="width: 371px; removed: static; removed 10px; height: 232px" valign="top" >
           <asp:UpdatePanel ID="Panel1" runat="server">
           <ContentTemplate>
                <asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="False" 
                    CellPadding="4" ForeColor="#333333" GridLines="None" 
                    onpageindexchanging="gvFiles_PageIndexChanging" 
                    onrowcommand="gvFiles_RowCommand" onrowdatabound="gvFiles_RowDataBound" 
                     Width="370px">
                    <AlternatingRowStyle BackColor="White" Width="700px" Font-Size="Small" />
                    <Columns>
                        <asp:BoundField DataField="FullPath" HeaderText="FileName" SortExpression="FullPath">
                        </asp:BoundField>
                        <asp:TemplateField HeaderText="Name" SortExpression="FullPath">
                            <ItemTemplate>
                                <asp:LinkButton runat="server" ID="lbFolderItem" Text='<%#Eval("FullPath")%>'  
                                CommandName="OpenFolder" CommandArgument='<%# Eval("FullPath") %>' >
                                </asp:LinkButton>
                                <asp:Literal runat="server" ID="ltlFileItem"></asp:Literal>                         
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="Extention" HeaderText="Ext" SortExpression="Extention">
                        </asp:BoundField>
                        <asp:BoundField DataField="Size" DataFormatString="{0:N0}" HeaderText="Size" HtmlEncode="False"
                            SortExpression="Size">
                            <ItemStyle HorizontalAlign="Right" Wrap="False" />
                        </asp:BoundField>
                        <asp:BoundField DataField="LastWriteTime" DataFormatString="{0:d}" HeaderText="Date Modified"
                            HtmlEncode="False" SortExpression="LastWriteTime">
                            <ItemStyle HorizontalAlign="Right" Wrap="False" />
                        </asp:BoundField>
                    </Columns>
                    <EditRowStyle BackColor="#2461BF" />
                    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="#EFF3FB" />
                    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />    
                </asp:GridView>
           </ContentTemplate>
           </asp:UpdatePanel>
        </td>
        <td style="width: 100%; removed: static; height: 100%" valign="top">
            <asp:TextBox ID="tbxContents" runat="server" Font-Names="Courier New" Font-Size="Small"
            Height="508px" ReadOnly="True" TextMode="MultiLine" Visible="True" Width="99%"
            Wrap="False" EnableViewState="False"></asp:TextBox>
        </td>
    </tr>
</table>
<asp:HiddenField ID="HiddenField1" runat="server" />



CodeBehind Control
C#
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                ShowEdit(false);        
        }

        void Page_PreRender(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                if(DirPath!="None")
                    PopulateGrid();   
            }
        }

        public override void DataBind()
        {
            if (DirPath != "None")
                PopulateGrid();
        }

        protected void PopulateGrid()
        {
            try
            {
                DataTable gvSource = DisplayFilesInGridView();
                DataRow gvRow;

                //Get All Folders Or Directories and add in table
                DirectoryInfo directory = new DirectoryInfo(@DirPath);//(@"c:\inetpub");
                DirectoryInfo[] subDirectories = directory.GetDirectories();
                foreach (DirectoryInfo dirInfo in subDirectories)
                {
                    gvRow = gvSource.NewRow();
                    gvRow["FullPath"] = dirInfo.Name;
                    gvRow["Extention"] = "Directory";
                    gvRow["Size"] = 0;
                    gvRow["LastWriteTime"] = dirInfo.LastWriteTime;
                    gvRow["IsFolder"] = 1;
                    gvRow["ImageUrl"] = @"~\Images\Folder.gif";
                    gvSource.Rows.Add(gvRow);                    
                }

                //Get files in all directories 
                FileInfo[] files = directory.GetFiles("*.*", SearchOption.AllDirectories);
                foreach (FileInfo fileInfo in files)
                {
                    bool canView = false;
                    try
                    {
                        string ext = ConfigurationManager.AppSettings["ViewExt"];
                        string[] extensions = ext.Split(';');
                        foreach (string extension in extensions)
                        {
                            if (String.Compare(fileInfo.Extension, extension, true) == 0)
                            {
                                canView = true;
                                break;
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }

                    if (canView)
                    {
                        gvRow = gvSource.NewRow();
                        gvRow["FullPath"] = fileInfo.Name;
                        gvRow["Size"] = fileInfo.Length;
                        gvRow["Extention"] = "File";
                        gvRow["LastWriteTime"] = fileInfo.LastWriteTime;
                        gvRow["IsFolder"] = 0;
                        //could do a switch to get correct image for each file type
                        switch (fileInfo.Extension)
                        {
                            case ".txt":
                            case ".log":
                                gvRow["ImageUrl"] = @"~\Images\page.gif";
                                break;
                            case ".bat":
                                gvRow["ImageUrl"] = @"~\Images\BAT.ico";
                                break;
                            case ".ini":
                                gvRow["ImageUrl"] = @"~\Images\INI.ico";
                                break;
                            case ".config":
                                gvRow["ImageUrl"] = @"~\Images\XML.ico";
                                break;
                            case ".aspx":
                                gvRow["ImageUrl"] = @"~\Images\ASPX.gif";
                                break;
                            case ".xml":
                                gvRow["ImageUrl"] = @"~\Images\XML.ico";
                                break;
                            default:
                                gvRow["ImageUrl"] = @"~\Images\page.gif";
                                break;
                        }
                        //gvRow["ImageUrl"] = @"~\Images\Windows.gif";
                        gvSource.Rows.Add(gvRow);
                    }
                    else if (String.Compare(fileInfo.Extension, ".exe", true) == 0 ||
                            String.Compare(fileInfo.Extension, ".dll", true) == 0)
                    {
                        //tbxContents.Text = String.Format("Version:\t{0}\nDateModified:\t{1}\nSize(bytes):\t{2}",
                        //    System.Diagnostics.FileVersionInfo.GetVersionInfo(node.Value).ProductVersion,
                        //    dt.ToLocalTime().ToString(), fi.Length);
                        //lblFile.Text = node.Value + "  [Date Modified: " + dt.ToLocalTime().ToString() + "]";
                        ShowEdit(true);
                    }
                    else
                    {
                        lblDateMod.Text = "Current File/Dir Last Modified on: " + fileInfo.LastWriteTimeUtc.ToString();
                        ShowEdit(false);
                    }
                }


                gvFiles.DataSource = gvSource;
                gvFiles.DataBind();
            }
            catch (Exception ex)
            {
                tbxContents.Text = ex.Message;
            }
        }

        private DataTable DisplayFilesInGridView()
        {
            DataTable dtGvSource = new DataTable();
            dtGvSource.Columns.Add("FullPath", typeof(String));
            dtGvSource.Columns.Add("Extention", typeof(String));
            dtGvSource.Columns.Add("size", typeof(Int32));
            dtGvSource.Columns.Add("LastWriteTime", typeof(DateTime));
            dtGvSource.Columns.Add("IsFolder", typeof(Boolean));
            dtGvSource.Columns.Add("ImageUrl", typeof(String));            
            return dtGvSource;
        }

protected void gvFiles_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvFiles.PageIndex = e.NewPageIndex;

            PopulateGrid();
        }

        protected void gvFiles_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "OpenFolder")
            {
                if (string.CompareOrdinal(e.CommandArgument.ToString(), "..") == 0)
                {
                    var currentFullPath = this.CurrentFolder;
                    if (currentFullPath.EndsWith("\\") || currentFullPath.EndsWith("/"))
                        currentFullPath = currentFullPath.Substring(0, currentFullPath.Length - 1);

                    currentFullPath = currentFullPath.Replace("/", "\\");

                    var folders = currentFullPath.Split("\\".ToCharArray());

                    this.CurrentFolder = string.Join("\\", folders, 0, folders.Length - 1);
                }
                else
                    this.CurrentFolder = Path.Combine(this.CurrentFolder, e.CommandArgument as string);


                PopulateGrid();
            }
        }

        protected void gvFiles_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var item = e.Row.DataItem as FileSystemItemCS;

                if (item.IsFolder)
                {
                    var lbFolderItem = e.Row.FindControl("lbFolderItem") as LinkButton;
                    lbFolderItem.Text = string.Format(@"<img src=""{0}"" alt="""" /> {1}", Page.ResolveClientUrl("~/Images/folder.png"), item.Name);
                }
                else
                {
                    var ltlFileItem = e.Row.FindControl("ltlFileItem") as Literal;
                    if (this.CurrentFolder.StartsWith("~"))
                        ltlFileItem.Text = string.Format(@"<a href=""{0}"" target=""_blank"">{1}</a>",
                                Page.ResolveClientUrl(string.Concat(this.CurrentFolder, "/", item.Name).Replace("//", "/")),
                                item.Name);
                    else
                        ltlFileItem.Text = item.Name;
                }
            }
        }


FileSystemItemCS.cs
C#
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SrvViewingTool
{
    public class FileSystemItemCS
    {
        public FileSystemItemCS(FileInfo file)
        {
            this.Name = file.Name;
            this.FullName = file.FullName;
            this.Size = file.Length;
            this.CreationTime = file.CreationTime;
            this.LastAccessTime = file.LastAccessTime;
            this.LastWriteTime = file.LastWriteTime;
            this.IsFolder = false;
        }

        public FileSystemItemCS(DirectoryInfo folder)
        {
            this.Name = folder.Name;
            this.FullName = folder.FullName;
            this.Size = null;
            this.CreationTime = folder.CreationTime;
            this.LastAccessTime = folder.LastAccessTime;
            this.LastWriteTime = folder.LastWriteTime;
            this.IsFolder = true;
        }

        public string Name { get; set; }
        public string FullName { get; set; }
        public long? Size { get; set; }
        public DateTime CreationTime { get; set; }
        public DateTime LastAccessTime { get; set; }
        public DateTime LastWriteTime { get; set; }
        public bool IsFolder { get; set; }

        public string FileSystemType
        {
            get
            {
                if (this.IsFolder)
                    return "File folder";
                else
                {
                    var extension = Path.GetExtension(this.Name);

                    if (IsMatch(extension, ".txt"))
                        return "Text file";
                    else if (IsMatch(extension, ".pdf"))
                        return "PDF file";
                    else if (IsMatch(extension, ".doc", ".docx"))
                        return "Microsoft Word document";
                    else if (IsMatch(extension, ".xls", ".xlsx"))
                        return "Microsoft Excel document";
                    else if (IsMatch(extension, ".jpg", ".jpeg"))
                        return "JPEG image file";
                    else if (IsMatch(extension, ".gif"))
                        return "GIF image file";
                    else if (IsMatch(extension, ".png"))
                        return "PNG image file";


                    // If we reach here, return the name of the extension
                    if (string.IsNullOrEmpty(extension))
                        return "Unknown file type";
                    else
                        return extension.Substring(1).ToUpper() + " file";
                }
            }
        }

        private bool IsMatch(string extension, params string[] extensionsToCheck)
        {
            foreach (var str in extensionsToCheck)
                if (string.CompareOrdinal(extension, str) == 0)
                    return true;

            // If we reach here, no match
            return false;
        }
    }
}
Tags: C#, ASP.NET, Gridview

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900