码迷,mamicode.com
首页 > 其他好文 > 详细

添加文件夹获得其树形结构,并构建其节点

时间:2015-01-27 20:11:34      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

定义文件信息

public class MyFileInfo
{
public string FileName { get; set; }//文件名
public string FilePath { get; set; }//文件路径
public long FileSize { get; set; }//文件大小
public string ParentPath { get; set; }//父路径
public string RelativePath { get; set; }//相对路径
public bool IsFile { get; set; }//是否为文件

//重写Equals方法,以便通过该值是否相等判断两个对象是否相等,在List中可以直接使用Contain方法确定是否已添加该项

public override bool Equals(object fileList)
{
if (this.FilePath.Equals(((CDBurnFileInfo)fileList).FilePath))
{
return true;
}
else
{
return false;
}
}
}

添加文件的方法

private void AddFile(TreeNode parentNode, string filePath)
{
MyFileInfo fl = new MyFileInfo();
fl.FilePath = filePath;
fl.FileName = Path.GetFileName(filePath);
fl.FileSize = new FileInfo(filePath).Length;
fl.IsFile = true;

if (!alFileList.Contains(fl))
{

TreeNode node = new TreeNode();
node.Text = fl.FileName;//节点显示名称

node.Name = fl.FilePath;
if (parentNode == null)
{
tvFileList.Nodes.Add(node);

}
else
{
node.Tag = parentNode.Name;//父节点path
parentNode.Nodes.Add(node);
fl.ParentPath = parentNode.Name;
}
alFileList.Add(fl);
}
}

//添加文件夹方法,通过递归将选择的文件夹下内容全部添加

private void AddFileOrDirectory(TreeNode parentNode,string filePath)
{
//parentPath
DirectoryInfo dir = new DirectoryInfo(filePath);
//不是目录 ,是文件
if (!dir.Exists)
{
AddFile(parentNode, filePath);
}
else
{
FileSystemInfo[] files = dir.GetFileSystemInfos();
//for (int i = 0; i < files.Length; i++)
MyFileInfo fl = new MyFileInfo();
TreeNode node = new TreeNode();
fl.FilePath = filePath;
fl.FileName = new DirectoryInfo(filePath).Name;
fl.IsFile = false;
if (!alFileList.Contains(fl))
{
node.Text = fl.FileName;
node.Tag = fl.FilePath;
node.Name = fl.FilePath;
if (parentNode == null)
{
tvFileList.Nodes.Add(node);
}
else
{
node.Tag = parentNode.Name;//父节点path
parentNode.Nodes.Add(node);
fl.ParentPath = parentNode.Name;
}
alFileList.Add(fl);
foreach (FileSystemInfo fsi in files)
{
FileInfo file = fsi as FileInfo;
//是文件
if (file != null)
{
AddFile(node, file.FullName);
}
//对于子目录,进行递归调用
else
AddFileOrDirectory(node, fsi.FullName);

}
}
}

 

}

 

//得到相对路径方法

string GetParentDir(CDBurnFileInfo fl)
{
string result = string.Empty;
if (fl.ParentPath != null)
{
CDBurnFileInfo cdbFileInfo= alFileList.Find(u => (u.FilePath == fl.ParentPath));
result = cdbFileInfo.FileName+"\\"+result;
result = GetParentDir(cdbFileInfo)+result;

}
return result;
}

在界面可以直接调用AddFileOrDirectory,传入文件或文件夹路径将其整个结构按树形结构Treeview构建完成。

构建完成后在,遍历文件列表,通过GetParentDir方法得到相对路径。

添加文件夹获得其树形结构,并构建其节点

标签:

原文地址:http://www.cnblogs.com/lvdong-1986/p/4253764.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!