Display Folders and Files in ListView - c#

I created a function in a Windows Form Application that allows users to view a folder structure (TreeForm) and the files within the folders in a ListView. Now, I need to create the same function for a WebForm application. I attempted to use the same code but have found that the asp.net webform controls do not contain the same properties as the winform. Below is part of the code which I cannot determine how to convert so that it maybe used with on a webform page. Does anyone now how to convert the following code so that it can be used with an asp.net webform? Any assistance would be greatly appreciated.
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
ListView1.Items.Clear();
ListViewItem.ListViewSubItem[] subItems;
List<string> permittedFoldersFiles = new List<string>();
if (permittedFoldersFiles.Contains(dir.Name))
{
item = new ListViewItem(dir.Name, 0);
subItems = new ListViewItem.ListViewSubItem[]
{new ListViewItem.ListViewSubItem(item, "Directory"),
new ListViewItem.ListViewSubItem(item,
dir.LastAccessTime.ToShortDateString())};
item.SubItems.AddRange(subItems);
listView1.Items.Add(item);
}
}

Try use this sample it's work very well
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DirectoryInfo rootInfo = new DirectoryInfo(Server.MapPath("~/MyFolder/"));
this.PopulateTreeView(rootInfo, null);
}
}
private void PopulateTreeView(DirectoryInfo dirInfo, TreeNode treeNode)
{
foreach (DirectoryInfo directory in dirInfo.GetDirectories())
{
TreeNode directoryNode = new TreeNode
{
Text = directory.Name,
Value = directory.FullName
};
if (treeNode == null)
{
//If Root Node, add to TreeView.
TreeView1.Nodes.Add(directoryNode);
}
else
{
//If Child Node, add to Parent Node.
treeNode.ChildNodes.Add(directoryNode);
}
//Get all files in the Directory.
foreach (FileInfo file in directory.GetFiles())
{
//Add each file as Child Node.
TreeNode fileNode = new TreeNode
{
Text = file.Name,
Value = file.FullName,
Target = "_blank",
NavigateUrl = (new Uri(Server.MapPath("~/"))).MakeRelativeUri(new Uri(file.FullName)).ToString()
};
directoryNode.ChildNodes.Add(fileNode);
}
PopulateTreeView(directory, directoryNode);
}
}

Related

How to make difference between FileInfo and DirectoryInfo in a file explorer in list view

I would like to make a file explorer with Windows Forms, i already have done a few things, but when i would like to use the DoubleClick event of my ListView I dont know how to code that file explorer needs to act differently when I make the doubleclick on a file or a folder.
My goal is:
Clicking on a file - Loads its text into a TextBox
Clicking on a directory - Opens it and loads it into the listview.
I know how to do 1. and 2. as well, I just don't know how can I make my DoubleClick function know what the selected item in ListView was 1. or 2.
I build my ListView like this:
private void miOpen_Click(object sender, EventArgs e)
{
InputDialog dlg = new InputDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
DirectoryInfo parentDI = new DirectoryInfo(dlg.Path);
listView1.Items.Clear();
try
{
foreach (DirectoryInfo df in parentDI.GetDirectories())
{
ListViewItem lvi = new ListViewItem(new string[] {
df.Name, df.Parent.ToString(),
df.CreationTime.ToShortDateString(), df.FullName });
listView1.Items.Add(lvi);
}
foreach (FileInfo fi in parentDI.GetFiles())
{
ListViewItem lvi = new ListViewItem(new string[] {
fi.Name, fi.Length.ToString(),
fi.CreationTime.ToShortDateString(), fi.FullName } );
listView1.Items.Add(lvi);
}
}
catch { }
}
}
Add the DirectoryInfo or the FileInfo objects to the Tag property of the ListViewItem. I.e
...
var lvi = new ListViewItem(new string[] {
df.Name,
df.Parent.ToString(),
df.CreationTime.ToShortDateString(),
df.FullName
});
lvi.Tag = df;
listView1.Items.Add(lvi);
...
or for the file info:
lvi.Tag = fi;
Then, after having selected an item in the listview:
private void btnTest_Click(object sender, EventArgs e)
{
// Show the first item selected as an example.
if (listView1.SelectedItems.Count > 0) {
switch (listView1.SelectedItems[0].Tag) {
case DirectoryInfo di:
MessageBox.Show($"Directory = {di.Name}");
break;
case FileInfo fi:
MessageBox.Show($"File = {fi.Name}");
break;
default:
break;
}
}
}
Try this code:
FileAttributes fileAttributes = File.GetAttributes("C:\\file.txt");
if (fileAttributes.HasFlag(FileAttributes.Directory))
Console.WriteLine("This path is for directory");
else
Console.WriteLine("This path is for file");

TreeView and listview in c#

I have a TreeView that shows all the folders on the computer.
How can I see all the files within a particular folder that in the TreeView?
try this:
private void button1_Click(object sender, EventArgs e)
{
treeView1.ShowNodeToolTips = true;
DirectoryInfo d = new DirectoryInfo("C:\\projects");
GetAllDirectories(d, null);
}
void GetAllDirectories(DirectoryInfo d, TreeNode nodeToAddChilds)
{
if (treeView1.Nodes.Count == 0)
{
TreeNode root = new TreeNode();
root.ToolTipText = GetFileNames(d);
root.Text = d.Name;
treeView1.Nodes.Add(root);
nodeToAddChilds = root;
}
DirectoryInfo[] dirList = d.GetDirectories();
foreach (DirectoryInfo oneDir in dirList)
{
if (oneDir.Name.StartsWith("$"))
{
// Just to avoid system permission limitations
continue;
}
TreeNode newChild = new TreeNode();
newChild.ToolTipText = GetFileNames(oneDir);
newChild.Text = oneDir.Name;
nodeToAddChilds.Nodes.Add(newChild);
GetAllDirectories(oneDir, newChild);
}
}
string GetFileNames(DirectoryInfo d)
{
string files = "files:\r\n";
FileInfo[] allFiles = d.GetFiles();
foreach (FileInfo oneFile in allFiles)
{
files += oneFile.Name + "\r\n";
}
return files;
}
private void treeView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
// Get the selected node.
TreeNode node = treeView1.SelectedNode;
DirectoryInfo d = new DirectoryInfo(node.text);
FileInfo[] Files = d.GetFiles();
}

How to capture changed Select/UnSelected Checkbox Node in a TreeView

I have an asp Treeview which i made for my understanding.
I would like to capture all the check and uncheck checkboxes node user selects.
I have tried to use a button click event in which i check for a CheckNodes. But i would like to know how to get the UnSelected nodes before he click the Save Button.
As per code,
This is the format of my treeview
On Page Load only 3 nodes are checked.
What if the user unselects few node and presses the save button.
How do i know capture the information of checkbox selected/Unselect on postback.
User Action
Selects -- Head1Child1GrandChild1
Unselects -- Head1Child2 &&
Head1Child3
Expected Result : Need to capture checkbox
Selects -- Head1Child1 && Head1Child1GrandChild1 (Code in Save_Click)
AND Also need to capture
Unselects -- Head1Child2 &&
Head1Child3
The given treeview is just a prototype to understand the problem for me. Imagine if there is 1000 nodes and user selects some node and unselects the selected node . I just want to get those unselected and selected node only. Thats it.
Thank you for your time.
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeView1" ShowCheckBoxes="All" Showlines="true" runat="server"></asp:TreeView>
<asp:Button ID="Button1" runat="server" OnClick="Save_Click" Text="Save" />
<br />
</div>
</form>
</body>
//CS Code
//TreeView on a PageLoad.
//It will create TreeView with all Checkbox checked
// If the user Unselects one check box how do i capture that in a event ?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback)
{
TreeNode tNode1 = new TreeNode();
tNode1.Text = "HeadNode1";
tNode1.Value = "HeadNode1";
TreeNode h1ChildNode1 = new TreeNode();
h1ChildNode1.Text = "Head1Child1";
tNode1.ChildNodes.Add(h1ChildNode1);
TreeNode h1GrandChild1 = new TreeNode();
h1GrandChild1.Text = "Head1Child1Grand1";
h1ChildNode1.ChildNodes.Add(h1GrandChild1);
TreeNode h1ChildNode2 = new TreeNode();
h1ChildNode2.Text = "Head1Child2";
tNode1.ChildNodes.Add(h1ChildNode2);
TreeNode h1ChildNode3 = new TreeNode();
h1ChildNode3.Text = "Head1Child3";
tNode1.ChildNodes.Add(h1ChildNode3);
TreeView1.Nodes.Add(tNode1);
TreeNode tNode2 = new TreeNode();
tNode2.Text = "HeadNode2";
tNode2.Value = "HeadNode2";
TreeView1.Nodes.Add(tNode2);
ServerSideChangeSelection(TreeView1, true);
}
protected TreeView ServerSideChangeSelection(TreeView t, bool check)
{
foreach (TreeNode tn in t.Nodes)
{
tn.Checked = false;
if (tn.ChildNodes.Count > 0)
{
foreach (TreeNode childNd in tn.ChildNodes)
{
childNd.Checked = check;
}
}
}
return t;
}
}
//Save Button Click for CheckNodes. Missing UnSelect Nodes ??
protected void Save_Click(object sender, EventArgs e)
{
List<string> checkNodes = new List<string>();
List<string> unCheckNodes = new List<string>();
foreach (var item in TreeView1.CheckedNodes)
{
checkNodes.Add(item.ToString());
}
}
I will make some changes to your code:
Created a property like below:
public List<TreeNode> Nodes
{
get
{
if (HttpContext.Current.Session["Nodes"] == null)
{
HttpContext.Current.Session["Nodes"] = new List<TreeNode>();
}
return HttpContext.Current.Session["Nodes"] as List<TreeNode>;
}
set
{
HttpContext.Current.Session["Nodes"] = value;
}
}
In your page_load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TreeNode tNode1 = new TreeNode();
tNode1.Text = "HeadNode1";
tNode1.Value = "HeadNode1";
TreeNode h1ChildNode1 = new TreeNode();
h1ChildNode1.Text = "Head1Child1";
tNode1.ChildNodes.Add(h1ChildNode1);
TreeNode h1GrandChild1 = new TreeNode();
h1GrandChild1.Text = "Head1Child1Grand1";
h1ChildNode1.ChildNodes.Add(h1GrandChild1);
TreeNode h1ChildNode2 = new TreeNode();
h1ChildNode2.Text = "Head1Child2";
tNode1.ChildNodes.Add(h1ChildNode2);
TreeNode h1ChildNode3 = new TreeNode();
h1ChildNode3.Text = "Head1Child3";
tNode1.ChildNodes.Add(h1ChildNode3);
TreeView1.Nodes.Add(tNode1);
TreeNode tNode2 = new TreeNode();
tNode2.Text = "HeadNode2";
tNode2.Value = "HeadNode2";
TreeView1.Nodes.Add(tNode2);
ServerSideChangeSelection(TreeView1, true);
List<TreeNode> nodes = new List<TreeNode>();
foreach (TreeNode node in TreeView1.Nodes)
{
nodes.Add(node);
if (node.ChildNodes.Count > 0)
{
foreach (TreeNode childNode in node.ChildNodes)
{
nodes.Add(childNode);
}
}
}
Nodes = nodes;
}
}
Save_Click:
protected void Save_Click(object sender, EventArgs e)
{
List<TreeNode> unCheckNodes = new List<TreeNode>();
GetCheckUncheckTreeNodes(TreeView1.Nodes, ref unCheckNodes);
}
private void GetCheckUncheckTreeNodes(TreeNodeCollection nodeCollection, ref List<TreeNode> unCheckNodes)
{
if (Nodes != null)
{
foreach (TreeNode node in nodeCollection)
{
if (!node.Checked && Nodes.Any(x => x.Text == node.Text && x.Checked != node.Checked))
unCheckNodes.Add(node);
if (node.ChildNodes.Count > 0)
GetCheckUncheckTreeNodes(node.ChildNodes, ref unCheckNodes);
}
}
}

TreeView directories in C# WPF

I have this code in C# Windows Form Application, but I need it in WPF. Do you have any ideas?
private void button1_Click(object sender, EventArgs e)
{
ListDirectory(treeView1, "C:\\Users\\Patrik\\Pictures");
}
private void ListDirectory(TreeView treeView, string path)
{
treeView.Nodes.Clear();
var rootDirectoryInfo = new DirectoryInfo(path);
treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
}
private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeNode(directoryInfo.Name);
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Nodes.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
directoryNode.Nodes.Add(new TreeNode(file.Name));
return directoryNode;
}
Thanks for help.
In WPF instead of Nodes property is Items property and instead of TreeNode you should use TreeViewItem (msdn).
private void ListDirectory(TreeView treeView, string path)
{
treeView.Items.Clear();
var rootDirectoryInfo = new DirectoryInfo(path);
treeView.Items.Add(CreateDirectoryNode(rootDirectoryInfo));
}
private static TreeViewItem CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeViewItem { Header = directoryInfo.Name };
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Items.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
directoryNode.Items.Add(new TreeViewItem { Header = file.Name });
return directoryNode;
}

How to properly display icons in selfmade Windows Explorer?

I am working in C# WinForms. I have made a Windows Explorer that displays the logical directories and then when clicked on them, it shows the files in them in a ListView (old but tricky thing). I get the icons from the system, using:
Icon iconForFile = SystemIcons.WinLogo;
ListViewItem lv = new ListViewItem(filData, imageList1.Images.Count);
lv.Tag = file;
iconForFile = Icon.ExtractAssociatedIcon(file);
string Extension = Path.GetExtension(file);
if (!imageList1.Images.ContainsKey(file))
{
// If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file);
imageList1.Images.Add(file, iconForFile);
}
lv.ImageKey = file;
listView1.SmallImageList = imageList1;
Now the problem is this: it does show the icons when a directory at first-level is clicked but when I click the folders in any directory (ie. "C"), it doesn't show the icons in the subfolders of a directory. Please help me on how I can customize it. My full code is somewhat like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
PopulateTreeView(treeView1);
}
private void PopulateTreeView(TreeView tv)
{
string[] drives = Environment.GetLogicalDrives();
TreeNode MyCnode = new TreeNode();
MyCnode = new TreeNode("My Computer");
tv.Nodes.Add(MyCnode);
foreach (string drive in drives)
{
TreeNode nodeDrive = new TreeNode();
nodeDrive.Tag = drive;
nodeDrive.Text = drive;
tv.Nodes.Add(nodeDrive);
// tv.Nodes.Add();
// nodeDrive.EnsureVisible();
// treeView1.Refresh();
try
{
//add dirs under drive
if (Directory.Exists(drive))
{
foreach (string dir in Directory.GetDirectories(drive))
{
TreeNode node = new TreeNode();
node.Tag = dir;
node.Text = dir.Substring(dir.LastIndexOf(#"\") + 1);
node.ImageIndex = 1;
nodeDrive.Nodes.Add(node);
}
}
}
catch (Exception)
{
}
MyCnode.Expand();
}
}
public TreeNode GetDirectory(TreeNode parentNode)
{
DirectoryInfo d = new DirectoryInfo(parentNode.FullPath);
DirectoryInfo[] dInfo = d.GetDirectories()
.Where(di => !di.Attributes.HasFlag(FileAttributes.System))
.Where(di => !di.Attributes.HasFlag(FileAttributes.Hidden))
.ToArray();
parentNode.Nodes.Clear();
if (dInfo.Length > 0)
{
TreeNode treeNode = new TreeNode();
foreach (DirectoryInfo driSub in dInfo)
{
treeNode = parentNode.Nodes.Add(driSub.Name);
treeNode.Nodes.Add("");
}
}
return parentNode;
}
private void AddFiles(string strPath)
{
try
{
listView1.BeginUpdate();
listView1.Items.Clear();
//headers listview
// listView1.Columns.Add("File Name", 200);
//listView1.Columns.Add("Size", 80);
//listView1.Columns.Add("Last Accessed", 110);
string[] dirData = new string[3];
string[] filData = new string[3];
string[] files = Directory.GetFiles(strPath);
foreach (string file in files)
{
FileInfo finfo = new FileInfo(file);
FileAttributes fatr = finfo.Attributes;
string name = Path.GetFileNameWithoutExtension(file);
filData[0] = name;
filData[1] = finfo.Length.ToString();
filData[2] = File.GetLastAccessTime(file).ToString();
// Set a default icon for the file.
Icon iconForFile = SystemIcons.WinLogo;
ListViewItem lv = new ListViewItem(filData, imageList1.Images.Count);
lv.Tag = file;
iconForFile = Icon.ExtractAssociatedIcon(file);
string Extension = Path.GetExtension(file);
if (!imageList1.Images.ContainsKey(file))
{
// If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file);
imageList1.Images.Add(file, iconForFile);
}
lv.ImageKey = file;
listView1.SmallImageList = imageList1;
listView1.Items.Add(lv);
}
}
catch (Exception Exc) { MessageBox.Show(Exc.ToString()); }
listView1.EndUpdate();
}
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
string pathdoubleClicked = listView1.FocusedItem.Tag.ToString();
Process.Start(pathdoubleClicked);
}
private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
{
GetDirectory(e.Node);
treeView1.SelectedNode.Expand();
AddFiles(e.Node.FullPath.ToString());
}
}
for anyone still seeing this as an answer to a search, the assignment of the imagelist needs to be done before the items are added to the imagelist.
private void AddFiles(string strPath)
{
try
{
listView1.BeginUpdate();
listView1.Items.Clear();
listView1.SmallImageList = imageList1;

Categories

Resources