Search code examples
c#asp.nettreeviewfileinfodirectoryinfo

How to get full file path on Asp.net?


I'm using Asp.net treeview to show my directory including files. I want to show the file path once the user click on the treeview node. I'm using FullName property to get the path. The problem that I have is, treeview shows the full path only for the directory not for the file!

Here is my code

private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
    TreeNode directoryNode = new TreeNode(directoryInfo.Name);

    foreach (DirectoryInfo directory in directoryInfo.GetDirectories())
    {
        if (!directory.Attributes.ToString().Contains("Hidden"))
        {
            directoryNode.ChildNodes.Add(CreateDirectoryNode(directory));
            directoryNode.Value = directoryInfo.FullName; // Here I'm passing the directory path
        }
    }

    foreach (FileInfo file in directoryInfo.GetFiles())
    {
        if (File.GetAttributes(file.FullName).ToString().IndexOf("Hidden") == -1)
        {
            directoryNode.ChildNodes.Add(new TreeNode(file.Name));
            directoryNode.Value = file.FullName; // Here I'm passing the file path
        }
    }

    return directoryNode;
}

Update For some reason full path is not showing treeNode value for the file but directory!


Solution

  • You set value to the wrong node.

    Change

      directoryNode.ChildNodes.Add(new TreeNode(file.Name));  
      directoryNode.Value = file.FullName; // Here I'm passing the file path  
    

    To

      TreeNode fileNode = new TreeNode(file.Name, file.FullName);
      directoryNode.ChildNodes.Add(fileNode);
    

    This will set Value of the file node to it`s Full path