TreeView and listview in c# - 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();
}

Related

Display Folders and Files in ListView

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);
}
}

How can i get from a listView1 item(file) the file full path?

I have this in my designer:
On the right is the files in a listView1.
On the left is the directory main directory of this files treeView1.
I have this code in menu strip item clicked event :
void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Text == "Upload")
{
List<String> selected = new List<String>();
foreach (ListViewItem lvi in listView1.SelectedItems)
{
selected.Add(lvi.Text);
}
AllFiles = selected.ToArray();
Bgw.RunWorkerAsync();
}
}
The problem is that the file/s in AllFiles array are only the filenames for example: bootmgr or install.exe
But i need that in the All Files each file will have also it's full path for example:
c:\bootmgr or c:\install.exe or c:\test\test\example.txt
How can i add to AllFiles also the paths ?
I tried now:
void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Text == "Upload")
{
List<String> selected = new List<String>();
string dir = treeView1.SelectedNode.FullPath;
foreach (ListViewItem lvi in listView1.SelectedItems)
{
string g = Path.Combine(dir, lvi.Text);
selected.Add(g);
}
AllFiles = selected.ToArray();
Bgw.RunWorkerAsync();
}
}
And in form1:
private void FtpProgress_DoWork(object sender, DoWorkEventArgs e)
{
f = new FtpSettings();
f.Host = "ftP://ftp.newsxpressmedia.com";
f.Username = "...";
f.Password = "...";
files = TV_LV_Basic.ExplorerTree.AllFiles;
StringArrayUploadFiles(sender, e);
}
AllFiles contain the files and paths for example C:\test.txt
Then :
private void StringArrayUploadFiles(object sender, DoWorkEventArgs e)
{
try
{
foreach (string txf in files)
{
string fn = txf;
BackgroundWorker bw = sender as BackgroundWorker;
if (f.TargetFolder != "" && f.TargetFolder != null)
{
createDirectory(f.TargetFolder);
}
else
{
f.TargetFolder = Path.GetDirectoryName(txf);
//createDirectory(f.TargetFolder);
}
string UploadPath = String.Format("{0}/{1}{2}", f.Host, f.TargetFolder == "" ? "" : f.TargetFolder + "/", Path.GetFileName(fn));
Now in txf for example i have C:test.txt
Then in f.TargetFolder i have: C:
Then in UploadPath i have: ftp://ftp.newsxpressmedia.com/C:/eula.1031.txt
But instead C: i need it to look like: ftp://ftp.newsxpressmedia.com/C/eula.1031.txt
And there are sub directories for example then: ftp://ftp.newsxpressmedia.com/C/Sub/Dir/eula.1031.txt
In the menuStrip1_ItemClicked event when i select a file for example test.txt already in this event i did a mess.
FileInfo fi = new FileInfo("temp.txt");
Determine the full path of the file just created.
DirectoryInfo di = fi.Directory;
Figure out what other entries are in that directory.
FileSystemInfo[] fsi = di.GetFileSystemInfos();
to display directoryinfo fullname in console
Console.WriteLine("The directory '{0}' contains the following files and directories:", di.FullName);
Print the names of all the files and subdirectories of that directory.
foreach (FileSystemInfo info in fsi)
Console.WriteLine(info.Name);
Here

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 use treeView to list the Files within sub Directories without showing the root directory?

This code works fine:
private void Form1_Load(object sender, EventArgs e)
{
PopulateTree(#"C:\treeview", treeView1.Nodes.Add("I want to remove this node"));
}
public void PopulateTree(string dir, TreeNode node)
{
DirectoryInfo directory = new DirectoryInfo(dir);
foreach (DirectoryInfo d in directory.GetDirectories())
{
TreeNode t = new TreeNode(d.Name);
PopulateTree(d.FullName, t);
node.Nodes.Add(t);
}
foreach (FileInfo f in directory.GetFiles())
{
TreeNode t = new TreeNode(f.Name);
node.Nodes.Add(t);
}
}
BUT, I do not want to show the main(=root) directory(=folder) on the top of the list of sub-directories, I just want to show the sub-directoriesas shown down in the illustration.
Try this:
public void PopulateTree(string dir, TreeNode node)
{
DirectoryInfo directory = new DirectoryInfo(dir);
foreach (DirectoryInfo d in directory.GetDirectories())
{
TreeNode t = new TreeNode(d.Name);
if (node != null) node.Nodes.Add(t);
else treeView1.Nodes.Add(t);
PopulateTree(d.FullName, t);
}
foreach (FileInfo f in directory.GetFiles())
{
TreeNode t = new TreeNode(f.Name);
if (node != null) node.Nodes.Add(t);
else treeView1.Nodes.Add(t);
}
}
private void Form1_Load(object sender, EventArgs e)
{
PopulateTree(#"C:\treeview", null);
}
PopulateTree(#"C:\treeview", treeView1.Nodes);
public void PopulateTree(string dir, TreeNodeCollection nodes)
{
DirectoryInfo directory = new DirectoryInfo(dir);
foreach (DirectoryInfo d in directory.GetDirectories())
{
TreeNode t = new TreeNode(d.Name);
nodes.Add(t);
PopulateTree(d.FullName, t.Nodes);
}
foreach (FileInfo f in directory.GetFiles())
{
TreeNode t = new TreeNode(f.Name);
nodes.Add(t);
}
}

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