Проводник на С# с помощью treeview
Добавлено: 28 май 2010, 12:07
Подскажите пожалуйста как с помощью treeview составить список файлов и каталогов (как в проводнике)?
Код: Выделить всё
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace CustTV
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected string rootPath = @"D:\MyData";//<--- change initial folder name here
public string ff;
protected void FillTreeNode(string searchPath, ref TreeNode parentNode)
{
TreeNode nnode;
FileSystemInfo[] iteminfo = new DirectoryInfo(searchPath).GetFileSystemInfos();
for (int i = 0; i <= iteminfo.Length - 1; i++)
{
FileSystemInfo item = iteminfo.GetValue(i) as FileSystemInfo;
nnode = new TreeNode();
if (item.Attributes == FileAttributes.Directory)
{
{
nnode.Text = item.Name;
}
if (new DirectoryInfo(item.FullName).GetFileSystemInfos().Length != 0)
{
FillTreeNode(Path.Combine(searchPath, item.Name), ref nnode);
}
}
else
{
{
nnode.Text = item.Name;
}
}
parentNode.Nodes.Add(nnode);
}
parentNode.Expand();
}
public static string FlushText(string fn)
{
string txt;
// Open and read the file.
StreamReader r = File.OpenText(fn);
txt = GetText(r);
return txt;
}
public static string GetText(StreamReader r)
{
// read whole text
string line;
line = r.ReadToEnd();
r.Close();
return line;
}
private void Form1_Load(System.Object sender, System.EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
TreeNode rootNode = new TreeNode();
FillTreeNode(rootPath, ref rootNode);
this.treeView1.Nodes.Add(rootNode);
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
this.Text = "Select Text File Only";
this.button2.Text = "Show TreeView";
this.button1.Text = "Exit";
}
private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
{
ff = this.treeView1.SelectedNode.FullPath;
try
{
FileInfo fl = new FileInfo(ff);
// Look for a file extension, and open the file.
if (fl.Extension.ToUpper() == ".TXT")
{
System.Diagnostics.Process.Start(rootPath + ff);
}
}
// If the file is not found, handle the exception and inform the user.
catch
{
MessageBox.Show("File not found.");
}
}
}
}
Код: Выделить всё
private void button1_Click(object sender, EventArgs e)
{
string[] drives = Directory.GetLogicalDrives();
foreach (string s in drives)
{
TreeNode tn = treeView1.Nodes.Add(s);
tn.Nodes.Add("");
tn.Tag = "";
}
}
private String GetFullPath(TreeNode tn)
{
// Устанавливаем текуший узел на переданный в параметре.
TreeNode currNode = tn;
// В полное имя пока записываем текст,
// показываемый в текущем узле.
String fullPath = currNode.Text;
// Двигаемся к корню дерева.
while (currNode.Parent != null)
{
// Переходим на родительский узел.
currNode = currNode.Parent;
// К полному имени приписываем текст родитеского узла.
fullPath = currNode.Text + @"\" + fullPath;
}
// Возвращаем полный путь.
return fullPath + @"\";
}
private void AddTreeNodes(TreeNode tn)
{
TreeNode aux;
// Получаем полный путь для папки узла.
DirectoryInfo d = new DirectoryInfo(GetFullPath(tn));
// Массив для хранения подпапок.
DirectoryInfo[] ds;
string searchPattern = "*.jpg";
try
{
// Получаем все подпапки для папки.
ds = d.GetDirectories();
// Для каждой папки выводим ее имя и имена всех подпапок.
foreach (DirectoryInfo s in ds)
{
FileInfo[] files = s.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);
// Добавляем каждую подпапку.
aux = tn.Nodes.Add(s.Name);
// Устанавливаем для нее признак, что ее еще не раскрывали.
aux.Tag = "";
try
{
// Если она не пуста,
if (((s.GetDirectories().GetLength(0)) != 0) || (files.GetLength(0)!=0))
{
// то добавляем в нее фиктивный узел.
aux.Nodes.Add("");
}
foreach (FileInfo file in files)
{
aux.Nodes.Add(file.Name);
}
}
// Перехватываем исключение запрещенного доступа.
catch (UnauthorizedAccessException)
{
};
}
}
//Перехват общего исключения (например, если диск a: не вставлен).
catch (Exception)
{
}
}
private void NodeExpand(TreeNode tn)
{
// Если есть подузлы.
if (tn.Nodes.Count != 0)
{
// Если раскрываем в первый раз.
if (((string)tn.Tag) == "")
{
// Удаляем фиктивный узел.
tn.Nodes.RemoveAt(0);
// Добавляем подузлы.
AddTreeNodes(tn);
// Устнавливаем признак того, что
// узел уже раскрывали и добавили в него все подузлы.
tn.Tag = "+";
}
}
}
private void treeView1_BeforeExpand(object sender,
System.Windows.Forms.TreeViewCancelEventArgs e)
{
NodeExpand(e.Node);
}